search

Home  >  Q&A  >  body text

Reworded title: Why doesn't PHP handle "class not found" errors?

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粉475126941P粉475126941325 days ago487

reply all(2)I'll reply

  • P粉680000555

    P粉6800005552024-01-04 16:54:40

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

    reply
    0
  • P粉810050669

    P粉8100506692024-01-04 15:37:51

    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.

    reply
    0
  • Cancelreply