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

后端 未结 5 1054
不知归路
不知归路 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:32

    Because php emits fatal error when you ty to create new object of non existing class. To make it work you will need php >= 5.3 and autoload function, where you should try to look for file with class definition or throw your custom exception.

    0 讨论(0)
  • 2020-12-30 20:34

    You need to use class_exists to see if the class exists before you try and instantiate it.

    Incidentally, if you're using a class autoloader, be sure to set the second arg to true.

    0 讨论(0)
  • 2020-12-30 20:50

    php >= 7.0

    php can catch 'class not found' as Throwable

    try {
            return new $className($smartFormIdCode);
    } catch (\Throwable $ex) {
            return new SmartFormNull($smartformIdCode);
    }
    
    0 讨论(0)
  • 2020-12-30 20:52

    Because it's a fatal error. Use class_exists() function to check if class exist.

    Also: PHP is not Java - unless you redefined default error handler, it will raise errors and not throw exceptions.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题