简体   繁体   中英

PHP __NAMESPACE__ in trait

As traits are effectively copy/paste code I was expecting:

__NAMESPACE__

to provide the namespace of the class using it.

Unfortunately, for me, it appears to provide the namespace of the trait.

Why is this?

__NAMESPACE__ contains the namespace of where the code in which __NAMESPACE__ appears was written. It has "literal scope", as far as that concept applies here. The same goes for functions you call within other namespaces or objects you instantiate within other namespaces; they all refer to their own original namespace, not the one the code is currently running in.

Namespaces are really just influencing names, identifiers . For all intents and purposes this:

namespace Foo\Bar;

class Baz {}

is just shorthand for:

class Foo\Bar\Baz {}

which for all intents and purposes is equivalent to:

class Foo_Bar_Baz {}

Namespaces aren't resolved at runtime or have any real influence on the runtime, they're merely serving to prefix names while still allowing somewhat short syntax and not having to constantly write very long names.

__NAMESPACE__ refers to the "name prefix" of the current entity, like Foo_Bar above; nothing more, nothing less.

You're calling it from the context of a method inside the trait itself, so it's perfectly logical for it to return the trait's namespace.

If you're actually asking how to get the class's namespace, take a look here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM