Im folgenden Beispiel m?chte ich den Fehler abfangen und eine Null
-Klasse erstellen, wenn die Klasse nicht existiert.
Aber trotz meiner try/catch-Anweisung sagt mir PHP einfach 未找到 'SmartFormasdfasdf' 類
.
Wie kann man PHP dazu bringen, ?Class Not Found“-Fehler abzufangen?
<?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(); ?>
Danke @Mchl, so habe ich es gel?st:
public static function create($smartFormIdCode) { $className = 'SmartForm' . $smartFormIdCode; if(class_exists($className)) { return new $className($smartFormIdCode); } else { return new SmartFormNull($smartFormIdCode); } }
老問(wèn)題,但在 PHP7 中這是一個(gè)可捕獲的異常。盡管我仍然認(rèn)為 class_exists($class) 是一種更明確的方法。但是,您可以使用新的 \Throwable
異常類型執(zhí)行 try/catch 塊:
$className = 'SmartForm' . $smartFormIdCode; try { return new $className($smartFormIdCode); } catch (\Throwable $ex) { return new SmartFormNull($smartformIdCode); }
因?yàn)檫@是一個(gè)致命錯(cuò)誤。使用class_exists()函數(shù)檢查類是否存在。
另外:PHP 不是 Java - 除非您重新定義默認(rèn)錯(cuò)誤處理程序,否則它會(huì)引發(fā)錯(cuò)誤而不拋出異常。