Assuming I have the following classes in different files:
<?php
namespace MyNS;
class superclass {
public function getNamespace(){
return __NAMESPACE__;
}
}
?>
<?php
namespace MyNS\SubNS;
class childclass extends superclass { }
?>
If I instantiate “childclass” and call getNamespace() it returns “MyNS”.
Is there any way to get the current namespace from the child class without redeclaring the method?
I’ve resorted to creating a static $namespace variable in each class and referencing it using super::$namespace but that just doesn’t feel very elegant.
__NAMESPACE__is a compile time constant, meaning that it is only useful at compile time. You can think of it as a macro which where inserted will replace itself with the current namespace. Hence, there is no way to get__NAMESPACE__in a super class to refer to the namespace of a child class. You will have to resort to some kind of variable which is assigned in every child class, like you are already doing.As an alternative, you can use reflection to get the namespace name of a class:
See the PHP manual for more (unfinished) documentation. Note that you’ll need to be on PHP 5.3.0 or later to use reflection.