如果您將每個類別都放在不同的檔案中,此自動載入器將會找到您呼叫的每個類別。
它會從您在 $root 變數中指定的根目錄開始,遞迴地進入每個目錄。
您可以在 $dir_to_not_look_in 陣列中指定您不想進入的資料夾 (例如,您不會在 MVC 專案的 'view' 資料夾中找到任何類別);
spl_autoload_register(function($class) {
$root = 'my/root/path';
$file = $class . '.php';
$dir_to_not_look_in = array($directories, $to, $not, $look, $in);
if(!function_exists('load')) {
function load($dir, $file) {
if(file_exists($dir . '/' . $file)) {
require_once $dir . '/' . $file;
} else {
foreach(scandir($dir) as $value) {
if(is_dir($dir. '/' . $value) && !in_array($value, $dir_to_no_look_in))
load($dir. '/' . $value, $file);
}
}
};
}
load($root, $file);
});