动态获取 PHP 类命名空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13932289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:17:52  来源:igfitidea点击:

Get PHP class namespace dynamically

phpoopintrospection

提问by daveoncode

How can I retrieve a class namespace automatically?

如何自动检索类命名空间?

The magic var __NAMESPACE__is unreliable since in subclasses it's not correctly defined.

魔术变量__NAMESPACE__不可靠,因为在子类中它没有正确定义。

Example:

例子:

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 (it should be Ping\pong)

class Ping\pong\B extends Foo\bar\A-> __NAMESPACE__=== Foo\bar (应该是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?

ps:我注意到使用了同样的错误行为__CLASS__,但我解决了使用get_called_class()......有没有类似的东西get_called_class_namespace()?我怎样才能实现这样的功能?

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

更新:
我认为解决方案是在我自己的问题中,因为我意识到get_called_class()返回完全限定的类名,因此我可以从中提取命名空间:D ...无论如何,如果有更有效的方法,请告诉我;)

回答by shadyyx

The namespace of class Foo\Bar\Ais Foo\Bar, so the __NAMESPACE__is working very well. What you are looking for is probably namespaced classnamethat you could easily get by joining echo __NAMESPACE__ . '\\' . __CLASS__;.

class Foo\Bar\Ais的命名空间Foo\Bar,因此__NAMESPACE__运行良好。您正在寻找的可能是命名空间类名,您可以通过join轻松获得echo __NAMESPACE__ . '\\' . __CLASS__;

Consider next example:

考虑下一个例子:

namespace Foo\Bar\FooBar;

use Ping\Pong\HongKong;

class A extends HongKong\B {

    function __construct() {
        echo __NAMESPACE__;
    }
}

new A;

Will print out Foo\Bar\FooBarwhich is very correct...

将打印出来Foo\Bar\FooBar这是非常正确的...

And even if you then do

即使你那样做

namespace Ping\Pong\HongKong;

use Foo\Bar\FooBar;

class B extends FooBar\A {

    function __construct() {
        new A;
    }
}

it will echo Foo\Bar\FooBar, which again is very correct...

它会回声Foo\Bar\FooBar,这又是非常正确的......

EDIT:If you need to get the namespace of the nested class within the main that is nesting it, simply use:

编辑:如果您需要在嵌套它的 main 中获取嵌套类的命名空间,只需使用:

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), '\'));
    }
}

回答by David Lin

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

在 PHP 5.5 中,::class 可用,这使事情变得简单 10 倍。例如 A::class