从 PHP 中的超类获取子类命名空间
假设我在不同的文件中有以下类:
Assuming I have the following classes in different files:
<?php
namespace MyNS;
class superclass {
public function getNamespace(){
return __NAMESPACE__;
}
}
?>
<?php
namespace MyNSSubNS;
class childclass extends superclass { }
?>
如果我实例化childclass"并调用 getNamespace(),它会返回MyNS".
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?
我已经在每个类中创建了一个静态 $namespace 变量并使用 super::$namespace
引用它,但这感觉不是很优雅.
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__
是编译时常量,意味着它只在编译时有用.您可以将其视为一个宏,插入的位置将用当前命名空间替换自身.因此,没有办法让超类中的 __NAMESPACE__
来引用子类的命名空间.您将不得不求助于在每个子类中分配的某种变量,就像您已经在做的那样.
__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:
$reflector = new ReflectionClass('A\Foo'); // class Foo of namespace A
var_dump($reflector->getNamespaceName());
有关更多(未完成)文档,请参阅 PHP 手册.请注意,您需要使用 PHP 5.3.0 或更高版本才能使用反射.
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.
相关文章