当使用 SomeClass::class
语法获取类的 FQN 时,如果该类不存在,它只会输出 SomeClass
而不是抛出 fatal error 错误。
echo SomeClass::class; // SomeClass
$class = new SomeClass(); // Fatal Error: Uncaught Error: Class 'SomeClass' not found
$const = SomeClass::SOME_CONST; // Fatal Error: Uncaught Error: Class 'SomeClass' not found
这对我来说似乎是不可取的。为什么会发生这种情况,有没有办法改变这种行为?
最佳答案
::class
关键字在编译时求值
来自manual
The class name resolution using
::class
is a compile time transformation. That means at the time the class name string is created no autoloading has happened yet. As a consequence, class names are expanded even if the class does not exist. No error is issued in that case.
这意味着,使用 ::class
不会调用自动加载器,也不会抛出错误。要调用自动加载器,您必须创建该类的实例或使用调用自动加载器的任何函数(即 class_exists
)
您可以通过定义一个简单的测试函数来解决这个问题,但我不确定这是否有很大的好处。
function class_or_fail($name) {
if (class_exists($name)) {
return $name;
}
throw new \Exception("Invalid class $name");
}
echo class_or_fail(SomeClass::class);
关于php - 为什么 PHP 在使用::class 时不抛出 class not found 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681153/