bcmcfc
bcmcfc

Reputation: 26755

What's the difference between "use \namespace\Class" and "use namespace\Class" in PHP?

Within our namespaced class files, there're various classes which have the namespace prefixed with a backslash and numerous others which don't.

Is there a difference between the two? Which is preferable to be using?

e.g.

use namespace\ui\User

vs

use \namespace\ui\User

where namespace itself represents the root folder where the namespaced classes reside.

Upvotes: 0

Views: 377

Answers (2)

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45721

From the PHP documentation:

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.

This means that you can, and should, omit the leading \ when importing/aliasing.

Upvotes: 2

LPunker
LPunker

Reputation: 613

how about if you use this method?

use

$_SERVER["DOCUMENT_ROOT"].'\namespace\ui\User'

Upvotes: 0

Related Questions