为什么PHP没有捕获“找不到类”错误?溶液:

2022-08-30 12:24:40

在下面的示例中,如果该类不存在,我想捕获错误并改为创建一个类。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);
  }
} 

答案 1

因为这是一个致命的错误。使用 class_exists() 函数检查类是否存在。

另外:PHP不是Java - 除非你重新定义了默认的错误处理程序,否则它会引发错误并且不会引发异常。


答案 2

老问题,但在 PHP7 中,这是一个可以捕获的例外。虽然我仍然认为这是一种更明确的方式。但是,您可以使用新的异常类型执行 try/catch 块:class_exists($class)\Throwable

$className = 'SmartForm' . $smartFormIdCode;
try {
    return new $className($smartFormIdCode);
} catch (\Throwable $ex) {
    return new SmartFormNull($smartformIdCode);
}

推荐