Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

oop - Get PHP class namespace dynamically

How can I retrieve a class namespace automatically?

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

Example:

class FooarA -> __NAMESPACE__ === Fooar

class PingpongB extends FooarA -> __NAMESPACE__ === Fooar (it should be Pingpong)

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The namespace of class FooBarA is FooBar, 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 FooBarFooBar;

use PingPongHongKong;

class A extends HongKongB {

    function __construct() {
        echo __NAMESPACE__;
    }
}

new A;

Will print out FooBarFooBar which is very correct...

And even if you then do

namespace PingPongHongKong;

use FooBarFooBar;

class B extends FooBarA {

    function __construct() {
        new A;
    }
}

it will echo FooBarFooBar, 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 PingPongHongKong;

use FooBarFooBar;

class B extends FooBarA {

    function __construct() {
        $a = new A;
        echo $a_ns = substr(get_class($a), 0, strrpos(get_class($a), '\'));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...