Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PHP class namespace dynamically

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 ;)

like image 777
daveoncode Avatar asked Dec 18 '12 11:12

daveoncode


1 Answers

In PHP 5.5, ::class is available which makes things 10X easier. E.g. A::class

like image 174
David Lin Avatar answered Oct 01 '22 08:10

David Lin