Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are PHP namespaces used with a leading slash

Tags:

namespaces

php

When using PHP namespaces, do you use them like:

\Foo\Bar->method()

or

Foo\Bar->method()

Notice the difference is only a leading slash. Or are both valid, and mean different things?

Thanks.

like image 774
Justin Avatar asked May 08 '13 02:05

Justin


1 Answers

The usage of a leading \ is like absolute and relative paths in filesystems. Best explained with code:

namespace test;
$dt = new DateTime();

fails, as we are using an relative path (without the leading \), and the current namespace test. And there is not class DateTime in this fictional namespace.

namespace test;
$dt = new \DateTime();

works as we are using an absolute namespaces path. As DateTime is in the global namespace \ it will be found.

Find more info in the PHP manual about namespaces

like image 107
hek2mgl Avatar answered Sep 21 '22 12:09

hek2mgl