在下面的示例中,如果类不存在,我希望捕获错误并创建一个Null
类。
但是,尽管我使用了try/catch语句,PHP还是简单地告诉我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,这就是我当时解决这个问题的方法:
public static function create($smartFormIdCode) {
$className = 'SmartForm' . $smartFormIdCode;
if(class_exists($className)) {
return new $className($smartFormIdCode);
} else {
return new SmartFormNull($smartFormIdCode);
}
}
发布于 2010-12-12 19:06:01
因为这是一个致命的错误。使用class_exists()函数检查类是否存在。
此外: PHP不是Java -除非您重新定义默认的错误处理程序,否则它将引发错误,而不会抛出异常。
发布于 2015-12-25 02:42:18
这是一个老问题,但在PHP7中这是一个容易捕获的异常。尽管我仍然认为class_exists($class)
是一种更明确的方式。但是,您可以使用新的\Throwable
异常类型执行一个try/catch块:
$className = 'SmartForm' . $smartFormIdCode;
try {
return new $className($smartFormIdCode);
} catch (\Throwable $ex) {
return new SmartFormNull($smartformIdCode);
}
发布于 2017-09-04 14:19:09
php >= 7.0
php可以将“class not found”捕获为Throwable
try {
return new $className($smartFormIdCode);
} catch (\Throwable $ex) {
return new SmartFormNull($smartformIdCode);
}
https://stackoverflow.com/questions/4421320
复制相似问题