在下面的示例中,如果该类不存在,我想捕获错误并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();
?>
Run Code Online (Sandbox Code Playgroud)
谢谢@Mchl,这就是我解决它的方式:
public static function create($smartFormIdCode) {
$className = 'SmartForm' . $smartFormIdCode;
if(class_exists($className)) {
return new $className($smartFormIdCode);
} else {
return new SmartFormNull($smartFormIdCode);
}
}
Run Code Online (Sandbox Code Playgroud)
Mch*_*chl 46
因为这是一个致命的错误.使用class_exists()函数检查类是否存在.
另外:PHP不是Java - 除非您重新定义了默认错误处理程序,否则它将引发错误而不会抛出异常.
Cha*_*rra 24
老问题,但在PHP7中,这是一个可捕获的异常.虽然我仍然认为这class_exists($class)是一种更明确的方式.但是,您可以使用新的\Throwable异常类型执行try/catch块:
$className = 'SmartForm' . $smartFormIdCode;
try {
return new $className($smartFormIdCode);
} catch (\Throwable $ex) {
return new SmartFormNull($smartformIdCode);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
php >= 7.0
php 可以将“找不到类”捕获为 Throwable
try {
return new $className($smartFormIdCode);
} catch (\Throwable $ex) {
return new SmartFormNull($smartformIdCode);
}
Run Code Online (Sandbox Code Playgroud)