有没有办法从PHP中的SPL自动加载器中抛出异常,以防它失败?它似乎不适用于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';
}
Run Code Online (Sandbox Code Playgroud)
当调用上面的代码时,没有异常的迹象,而是我得到一个标准的"致命错误:类'foobarDomain'在bla中找不到".并且脚本的执行终止.
Ion*_*tan 18
这不是一个错误,这是一个设计决定:
注意:
__autoload函数中抛出的异常无法在catch块中捕获并导致致命错误.
原因是可能有多个自动加载处理程序,在这种情况下,您不希望第一个处理程序抛出异常并绕过第二个处理程序.您希望您的第二个处理程序有机会自动加载其类.如果您使用的库使用自动加载功能,您不希望它绕过自动加载处理程序,因为它们会在自动加载器中抛出异常.
如果要检查是否可以实例化一个类,那么使用class_exists和传递true作为第二个参数(或者将其保留true为默认值):
if (class_exists('foobarDomain', $autoload = true)) {
$domain = new foobarDomain();
} else {
echo 'Class not found';
}
Run Code Online (Sandbox Code Playgroud)