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

Categories

0 votes
964 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...