为什么 PHP 没有捕获“找不到类"?错误? [英] Why doesn't PHP catch a "Class not found" error?
本文介绍了为什么 PHP 没有捕获“找不到类"?错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下示例中,如果该类不存在,我想捕获错误并创建一个 Null
类.
In the following example, if the class does not exist, I want to catch the error and create a Null
class instead.
但尽管我有 try/catch 语句,PHP 只是告诉我 Class 'SmartFormasdfasdf' not found
.
But in spite of my try/catch statements, PHP simply tells me Class 'SmartFormasdfasdf' not found
.
如何让 PHP 捕获找不到类"错误?
<?php
class SmartFormLogin extends SmartForm {
public function render() {
echo '<p>this is the login form</p>';
}
}
class SmartFormCodeWrapper extends SmartForm {
public function render() {
echo '<p>this is the code wrapper form</p>';
}
}
class SmartFormNull extends SmartForm {
public function render() {
echo '<p>the form "' . htmlentities($this->idCode) . '" does not exist</p>';
}
}
class SmartForm {
protected $idCode;
public function __construct($idCode) {
$this->idCode = $idCode;
}
public static function create($smartFormIdCode) {
$className = 'SmartForm' . $smartFormIdCode;
try {
return new $className($smartFormIdCode);
} catch (Exception $ex) {
return new SmartFormNull($smartformIdCode);
}
}
}
$formLogin = SmartForm::create('Login');
$formLogin->render();
$formLogin = SmartForm::create('CodeWrapper');
$formLogin->render();
$formLogin = SmartForm::create('asdfasdf');
$formLogin->render();
?>
解决方案:
谢谢@Mchl,我当时就是这样解决的:
Solution:
Thanks @Mchl, this is how I solved it then:
public static function create($smartFormIdCode) {
$className = 'SmartForm' . $smartFormIdCode;
if(class_exists($className)) {
return new $className($smartFormIdCode);
} else {
return new SmartFormNull($smartFormIdCode);
}
}
推荐答案
因为这是一个致命错误.使用 class_exists() 函数检查类是否存在.
Because it's a fatal error. Use class_exists() function to check if class exist.
另外:PHP 不是 Java - 除非您重新定义默认错误处理程序,否则它将引发错误而不是抛出异常.
Also: PHP is not Java - unless you redefined default error handler, it will raise errors and not throw exceptions.
这篇关于为什么 PHP 没有捕获“找不到类"?错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文