What is the main difference between these two lines?:
$obj = new ArrayObject();
&
$obj = new \ArrayObject();
When I used the first line I got an error: "Fatal error: Class '\Foo\Bar\ArrayObject' not found..."
and I am not too sure as to why I got this error? The second line seemed to have fixed the problem.
If you use:
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:
it means that ArrayObject is defined in global namespace.
In your example you probably have code something like that:
It won't work because you haven't defined
ArrayObject
inFoo\Bar
namespace.The above code is the same as:
And if
ArrayObject
is defined in global namespace (as probably in your case) you need to use code: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:
As you see
use ArrayObject;
was added before creating object to import ArrayObject from global namespace. Usinguse
you don't need to add (and you shouldn't) add leading backslash however it works the same as it wereuse \ArrayObject;
so above code is equivalent logically to:however as I said leading backslash in importing namespaces should not be used. Quoting PHP manual for that: