Dynamic namespace of PHP classes

How can I automatically get the class namespace?

The magic of var __NAMESPACE__ unreliable because it is not defined correctly in subclasses.

Example:

class Foo\bar\A β†’ __NAMESPACE__ === Foo \ bar

class Ping\pong\B extends Foo\bar\A β†’ __NAMESPACE__ === Foo \ bar (this should be Ping \ pong)

ps: I noticed the same wrong behavior using __CLASS__ , but I decided to use get_called_class() ... is there something like get_called_class_namespace() ? How to implement such a function?

UPDATE:
I think the solution is in my own question, since I realized that get_called_class() returns the full name of the class, and therefore I can extract the namespace from it: D ... In any case, if there is a more efficient approach, give me know;)

+7
source share
2 answers

The class Foo\Bar\A namespace class Foo\Bar\A is equal to Foo\Bar , so __NAMESPACE__ works very well. What you are looking for is probably the class name, which you can easily get by joining echo __NAMESPACE__ . '\\' . __CLASS__; echo __NAMESPACE__ . '\\' . __CLASS__; .

Consider the following example:

 namespace Foo\Bar\FooBar; use Ping\Pong\HongKong; class A extends HongKong\B { function __construct() { echo __NAMESPACE__; } } new A; 

Print Foo\Bar\FooBar , which is very correct ...

And even if you do

 namespace Ping\Pong\HongKong; use Foo\Bar\FooBar; class B extends FooBar\A { function __construct() { new A; } } 

it will echo Foo\Bar\FooBar , which again is very correct ...

EDIT: If you need to get the namespace of a nested class inside the main nested class, just use:

 namespace Ping\Pong\HongKong; use Foo\Bar\FooBar; class B extends FooBar\A { function __construct() { $a = new A; echo $a_ns = substr(get_class($a), 0, strrpos(get_class($a), '\\')); } } 
+9
source

In PHP 5.5, the :: class is available, which simplifies work by 10 times. For example. A::class

+9
source

All Articles