动态获取PHP类名称空间 [英] Get PHP class namespace dynamically
问题描述
如何自动检索类名称空间?
How can I retrieve a class namespace automatically?
魔术变量__NAMESPACE__
不可靠,因为在子类中定义不正确.
The magic var __NAMESPACE__
is unreliable since in subclasses it's not correctly defined.
示例:
class Foo\bar\A
-> __NAMESPACE__
=== Foo \ bar
class Foo\bar\A
-> __NAMESPACE__
=== Foo\bar
class Ping\pong\B extends Foo\bar\A
-> __NAMESPACE__
=== Foo \ bar(应该是Ping \ pong)
class Ping\pong\B extends Foo\bar\A
-> __NAMESPACE__
=== Foo\bar (it should be Ping\pong)
ps:我注意到使用__CLASS__
时出现了相同的错误行为,但是我使用get_called_class()
解决了...是否存在类似get_called_class_namespace()
的问题?如何实现这种功能?
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?
更新:
我认为解决方案是我自己的问题,因为我意识到get_called_class()
返回完全限定的类名,因此我可以从中提取名称空间:D
...无论如何,如果有更有效的方法,请告诉我;)
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 ;)
推荐答案
class Foo\Bar\A
的命名空间为Foo\Bar
,因此__NAMESPACE__
运行良好.您正在寻找的可能是以命名空间分隔的类名,只需加入echo __NAMESPACE__ . '\\' . __CLASS__;
即可轻松获得.
The namespace of class Foo\Bar\A
is Foo\Bar
, so the __NAMESPACE__
is working very well. What you are looking for is probably namespaced classname that you could easily get by joining echo __NAMESPACE__ . '\\' . __CLASS__;
.
考虑下一个示例:
namespace Foo\Bar\FooBar;
use Ping\Pong\HongKong;
class A extends HongKong\B {
function __construct() {
echo __NAMESPACE__;
}
}
new A;
将打印出Foo\Bar\FooBar
这是非常正确的...
Will print out Foo\Bar\FooBar
which is very correct...
即使您这样做
namespace Ping\Pong\HongKong;
use Foo\Bar\FooBar;
class B extends FooBar\A {
function __construct() {
new A;
}
}
它将回显Foo\Bar\FooBar
,这又是非常正确的...
it will echo Foo\Bar\FooBar
, which again is very correct...
编辑:如果您需要在嵌套类的主类中获取嵌套类的名称空间,只需使用:
If you need to get the namespace of the nested class within the main that is nesting it, simply 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), '\\'));
}
}
这篇关于动态获取PHP类名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!