Get child class namespace from superclass in PHP(从 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 { }
?>
如果我实例化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__ 是编译时常量,意味着它只在编译时有用.您可以将其视为一个宏,插入的位置将用当前命名空间替换自身.因此,没有办法让超类中的 __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 手册.请注意,您需要使用 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 中的超类获取子类命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 PHP 中的超类获取子类命名空间
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
