In the example below, I want to catch the error and create a Null
class if the class does not exist.
But despite my try/catch statements, PHP just tells me 'SmartFormasdfasdf' class
not found.
How to make PHP catch "Class Not Found" errors?
<?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(); ?>
Thanks @Mchl, this is how I solved it:
public static function create($smartFormIdCode) { $className = 'SmartForm' . $smartFormIdCode; if(class_exists($className)) { return new $className($smartFormIdCode); } else { return new SmartFormNull($smartFormIdCode); } }
Old question, but in PHP7 this is a catchable exception. Although I still think class_exists($class) is a more explicit approach. However, you can use the new
\Throwable
exception type to execute a try/catch block:Because this is a fatal error. Use the class_exists() function to check if a class exists.
Also: PHP is not Java - it raises errors without throwing exceptions unless you redefine the default error handler.