Namespacing does for functions and classes what scope does for variables. It allows you to use the same function or class name in different parts of the same program without causing a name collision.

In simple terms, think of a namespace as a person’s surname. If there are two people named “John” you can use their surnames to tell them apart.

<?php
namespace My\SpecialNamespace;
class MyClass
{
}

$object = new MyClass;



Then in another file we call it like this:

$object = new \My\SpecialNamespace\MyClass;



Another thing to watch out for is using classes in a different namespace. For example, most built-in PHP classes are located in the global top level namespace. For example, if you tried using the following code.

<?php
namespace My\SpecialNamespace;
class MyClass
{
    public function __construct()
    {
        $test = new DomDocument;
    }
}    
$object = new MyClass;


PHP would yell at you with the following error message

PHP Fatal error:  Class 'My\SpecialNamespace\DomDocument' not 
found in /path/to/some/file.php on line 7   



PHP assumed we wanted a class named My\SpecialNamespace\DomDocument. The same thing that lets us say new MyClass also means we need to be explicit with our other classes.
We have two options here:

1. Use leading slash, this tells PHP to use global class DomDocument;

$test = new \DomDocument;


2.Import that class with use. Then you can use DomDocument without leading slash.

use DomDocument;




This will work with any class, not just built-in PHP classes. Consider the Some\Other\Class\Thing class below.

<?php
namespace My\SpecialNamespace;
use Some\Other\Class\Thing;

$object = new \Some\Other\Class\Thing;
$object = new Thing;