在下面的示例中,如果該類(lèi)不存在,我想捕獲錯(cuò)誤并創(chuàng)建一個(gè) Null
類(lèi)。
但是盡管我有 try/catch 語(yǔ)句,PHP 只是告訴我 未找到 'SmartFormasdfasdf' 類(lèi)
。
如何讓 PHP 捕獲“未找到類(lèi)”錯(cuò)誤?
<?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); } }
老問(wèn)題,但在 PHP7 中這是一個(gè)可捕獲的異常。盡管我仍然認(rèn)為 class_exists($class) 是一種更明確的方法。但是,您可以使用新的 \Throwable
異常類(lèi)型執(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ù)檢查類(lèi)是否存在。
另外:PHP 不是 Java - 除非您重新定義默認(rèn)錯(cuò)誤處理程序,否則它會(huì)引發(fā)錯(cuò)誤而不拋出異常。