How to use objects from other namespaces and how to import namespaces in PHP

If you use:

$obj = new ArrayObject();

it means that ArrayObject is defined in current namespace. You can use this syntax where you are in global namespace (no namespace defined in current scope) or if ArrayObject is defined in the same namespace as current scope (example Foo\Bar).

And if you use:

$obj = new \ArrayObject();

it means that ArrayObject is defined in global namespace.

In your example you probably have code something like that:

namespace Foo\Bar;

$obj = new ArrayObject();

It won’t work because you haven’t defined ArrayObject in Foo\Bar namespace.

The above code is the same as:

namespace Foo\Bar;

$obj = new \Foo\Bar\ArrayObject();

And if ArrayObject is defined in global namespace (as probably in your case) you need to use code:

namespace Foo\Bar;

$obj = new \ArrayObject();

to accent that ArrayObject is not defined in Foo\Bar namespace;

One more thing – if you use ArrayObject in many places in your current namespace it might be not very convenient to add each time leading backslash. That’s why you may import namespace so you could use easier syntax:

namespace Foo\Bar;

use ArrayObject;

$obj = new ArrayObject();

As you see use ArrayObject; was added before creating object to import ArrayObject from global namespace. Using use you don’t need to add (and you shouldn’t) add leading backslash however it works the same as it were use \ArrayObject; so above code is equivalent logically to:

namespace Foo\Bar;

use \ArrayObject;

$obj = new ArrayObject();

however as I said leading backslash in importing namespaces should not be used. Quoting PHP manual for that:

Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not recommended, as import names must be fully qualified, and are not processed relative to the current namespace.

Leave a Comment