因此我們急需使用一個autoload呼叫堆疊,這樣spl的autoload系列函數就出現了。你可以使用spl_autoload_register註冊多個自訂的autoload函數。
如果你的PHP版本大於5.1的話,你就可以使用spl_autoload。先了解spl的幾個函數:
spl_autoload 是_autoload()的預設實現,它會去include_path$class_pclass_name(.php/.Sclass)
.專案中,通常方法如下(當類別找不到的時候才會被呼叫):
// 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.<classname>.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; } } });