本文介绍了从PHP中的超类获取子类命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在不同的文件中有以下类:

Assuming I have the following classes in different files:

<?php
    namespace MyNS;

    class superclass {

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

<?php
    namespace MyNS\SubNS;

    class childclass extends superclass { }
?>

如果我实例化childclass并调用getNamespace(),则返回MyNS。

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?

我已经求助于创建每个类中的一个静态$ namespace变量,并使用 super :: $ namespace 引用它,但这感觉不太优雅。

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.

推荐答案

__ NAMESPACE __ 是一个编译时常量,这意味着它只在编译时有用。您可以将其视为一个宏,其中inserted将使用当前命名空间替换自身。因此,没有办法在超类中获取 __ NAMESPACE __ 来引用子类的命名空间。您将不得不求助于在每个子类中分配的某种变量,就像您已经在做的那样。

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

参见了解更多(未完成的)文档。请注意,您需要使用PHP 5.3.0或更高版本才能使用反射。

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.

这篇关于从PHP中的超类获取子类命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 22:29