How can I retrieve a class namespace automatically?
The magic var __NAMESPACE__
is unreliable since in subclasses it's not correctly defined.
Example:
class Foo\bar\A
-> __NAMESPACE__
=== Foo\bar
class Ping\pong\B extends Foo\bar\A
-> __NAMESPACE__
=== Foo\bar (it should be Ping\pong)
ps: I noticed the same wrong behavior using __CLASS__
, but I solved using get_called_class()
... is there something like get_called_class_namespace()
? How can I implement such function?
UPDATE:
I think the solution is in my own question, since I realized get_called_class()
returns the fully qualified class name and thus I can extract the namespace from it :D
...Anyway if there is a more effective approach let me know ;)
In PHP 5.5, ::class is available which makes things 10X easier. E.g.
A::class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With