本文介绍了在SPL自动加载器中引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以防止PHP中的SPL自动加载器引发异常?在PHP 5.2.11下似乎不起作用.

Is there a way to throw exceptions from an SPL Autoloader in PHP in case it fails? It doesn't seem to work under PHP 5.2.11.

class SPLAutoLoader{

    public static function autoloadDomain($className) {
        if(file_exists('test/'.$className.'.class.php')){
            require_once('test/'.$className.'.class.php');
            return true;
        }       

        throw new Exception('File not found');
    }

} //end class

//start
spl_autoload_register( array('SPLAutoLoader', 'autoloadDomain') );

try{
    $domain = new foobarDomain();
}catch(Exception $c){
    echo 'File not found';
}

调用上面的代码时,没有异常的迹象,相反,我得到一个标准的致命错误:bla中找不到类'foobarDomain'".并且脚本的执行终止.

When the above code is called, there is no sign of an exception, instead I get a standard "Fatal error: Class 'foobarDomain' not found in bla". And the execution of the script terminates.

推荐答案

这不是错误,它是一个设计决策:

原因是可能有多个自动加载处理程序,在这种情况下,您不希望第一个处理程序抛出Exception并绕过第二个处理程序.您希望您的第二个处理程序有机会自动加载其类.如果您使用的库利用了自动加载功能,则您不希望它绕过自动加载处理程序,因为它们会在自动加载器内抛出异常.

The reason is that there may be more than one autoload handlers, in which case, you don't want the first handler to throw an Exception and bypass the second handler. You want your second handler to have a chance at autoloading its classes. If you use a library which makes use of the autoloading feature, you don't want it bypassing your autoload handler because they throw Exceptions inside their autoloader.

如果要检查是否可以实例化一个类,请使用 class_exists ,然后将true作为第二个参数传递(或忽略它,默认为true):

If you want to check whether or not you can instantiate a class, then use class_exists and pass true as the second argument (or leave it out, true is the default):

if (class_exists('foobarDomain', $autoload = true)) {
    $domain = new foobarDomain();
} else {
    echo 'Class not found';
}

这篇关于在SPL自动加载器中引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 20:30