在下面的示例中,如果该类不存在,我想捕获错误并创建一个 Null 类。
但是尽管我有 try/catch 语句,PHP 只是告诉我 未找到 'SmartFormasdfasdf' 类 。
如何让 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);
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
老问题,但在 PHP7 中这是一个可捕获的异常。尽管我仍然认为 class_exists($class) 是一种更明确的方法。但是,您可以使用新的
\Throwable异常类型执行 try/catch 块:$className = 'SmartForm' . $smartFormIdCode; try { return new $className($smartFormIdCode); } catch (\Throwable $ex) { return new SmartFormNull($smartformIdCode); }因为这是一个致命错误。使用class_exists()函数检查类是否存在。
另外:PHP 不是 Java - 除非您重新定义默认错误处理程序,否则它会引发错误而不抛出异常。