PHP 5.5 作为一项新功能实现了一种通过语法 ::class
检索类名的新方法:
<?php
namespace Testing;
class Test{}
echo Test::class; // Testing\Test;
这很完美,好吗?但是我和其他一些 friend 想知道的是,为什么当与未声明的类一起使用时,这种语法也会返回一个类名。例如:
<?php
echo UndeclaredClass::class; // UndeclaredClass
在其他几种情况下会引发错误,但此处不会。任何人都知道,如果可能的话,有具体的依据,为什么会发生这种情况?
它是否对后期静态绑定(bind)有任何影响,或者它只是这个全新功能的(临时)限制/错误?
最佳答案
终于有了一个正式的答案……相对而言。它是由 requinix@php.net 在 bu report 中识别的人提供给我的我创造了今天。唯一的异常(exception)是此人参与 PHP 开发的程度。
长话短说
PHP doesn't need ot know the definition of a class to get its fully-qualified name. All the required informations are available in compile-time so it doesn't need to load it.
导演剪辑版
namespace ,如用途,在编译时解析,即在文件执行之前编译时。这就是为什么要使用它们有严格的要求。
由于所有这些要求,当 PHP 遇到一个类名时,它可以立即知道它的完全限定名。将其视为文件系统,命名空间 将是相对位置的目录,使用 将是符号链接(symbolic link)。
类名可以是绝对的(“\Testing\Test”)或相对的(“Test”),如果是相对的,它可以是一个普通的名字。 [需要更多上下文]
namespace Testing {
echo Test::class; // \Testing + Test = \Testing\Test
}
或者一个别名:
use Testing\Test as AliasedTest;
echo AliasedTest::class; // AliasedTest + use = \Testing\Test
如果没有这些,自动加载将无法工作!
::class
只是一个新工具,用于公开 PHP 一直已知的信息。
This "extended answer" is pretty much the same of what I received as bug report. The reason of so much apparent copy & paste is because, originally, I built up this answer for another Stack Overflow Community
关于PHP 5.5 类名解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24461919/