Get PHP class namespace dynamically

十年热恋 提交于 2019-11-29 13:22:29

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__;.

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\FooBar which is very correct...

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...

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!