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
762 views
in Technique[技术] by (71.8m points)

inheritance - Get child class namespace from superclass in PHP

Assuming I have the following classes in different files:

<?php
    namespace MyNS;

    class superclass {

        public function getNamespace(){
            return __NAMESPACE__;
        }
    }
?>

<?php
    namespace MyNSSubNS;

    class childclass extends superclass { }
?>

If I instantiate "childclass" and call getNamespace() it returns "MyNS".

Is there any way to get the current namespace from the child class without redeclaring the method?

I've resorted to creating a static $namespace variable in each class and referencing it using super::$namespace but that just doesn't feel very elegant.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

__NAMESPACE__ is a compile time constant, meaning that it is only useful at compile time. You can think of it as a macro which where inserted will replace itself with the current namespace. Hence, there is no way to get __NAMESPACE__ in a super class to refer to the namespace of a child class. You will have to resort to some kind of variable which is assigned in every child class, like you are already doing.

As an alternative, you can use reflection to get the namespace name of a class:

$reflector = new ReflectionClass('A\Foo'); // class Foo of namespace A
var_dump($reflector->getNamespaceName());

See the PHP manual for more (unfinished) documentation. Note that you'll need to be on PHP 5.3.0 or later to use reflection.


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

...