Reworded title: Why doesn't PHP handle "class not found" errors?
P粉475126941
P粉475126941 2024-01-03 19:53:41
0
2
513

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();
?>

solution:

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);
  }
}


P粉475126941
P粉475126941

reply all(2)
P粉680000555

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:

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

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template