Why doesn't PHP catch a “Class not found” error?

后端 未结 5 1089
不知归路
不知归路 2020-12-30 20:20

In the following example, if the class does not exist, I want to catch the error and create a Null class instead.

But in spite of my try/catch statement

5条回答
  •  醉酒成梦
    2020-12-30 20:52

    Old question, but in PHP7 this is a catchable exception. Though I still think the class_exists($class) is a more explicit way to do it. However, you could do a try/catch block using the new \Throwable exception type:

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

提交回复
热议问题