时间:2021-07-01 10:21:17 帮助过:7人阅读
因此我们急需使用一个autoload调用堆栈,这样spl的autoload系列函数就出现了。你可以使用spl_autoload_register注册多个自定义的autoload函数。
如果你的PHP版本大于5.1的话,你就可以使用spl_autoload。先了解spl的几个函数:

spl_autoload 是_autoload()的默认实现,它会去include_path中寻找$class_name(.php/.inc)
实际项目中,通常方法如下(当类找不到的时候才会被调用):
// Example to auto-load class files from multiple directories using the SPL_AUTOLOAD_REGISTER method.
// It auto-loads any file it finds starting with class..php (LOWERCASE), eg: class.from.php, class.db.php
spl_autoload_register(function($class_name) {
// Define an array of directories in the order of their priority to iterate through.
$dirs = array(
'project/', // Project specific classes (+Core Overrides)
'classes/', // Core classes example
'tests/', // Unit test classes, if using PHP-Unit
);
// Looping through each directory to load all the class files. It will only require a file once.
// If it finds the same class in a directory later on, IT WILL IGNORE IT! Because of that require once!
foreach( $dirs as $dir ) {
if (file_exists($dir.'class.'.strtolower($class_name).'.php')) {
require_once($dir.'class.'.strtolower($class_name).'.php');
return;
}
}
}); 以上就介绍了PHP __autoload与spl_autoload,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。