PHP 5.1+ 引入 SPL(Standard PHP Library),提供 spl_autoload_register() 替代傳統 __autoload(),支持多自動加載函數棧,解決類庫衝突,是現代框架(Laravel、Symfony、ThinkPHP 等)的標準做法。
function __autoload($classname) {
if (is_file($classname . '.php')) include $classname . '.php';
elseif (is_file($classname . '.inc')) include $classname . '.inc';
}
__autoload,引入第三方庫時極易衝突。spl_autoload_extensions('.php,.inc,.class.php');set_include_path(get_include_path() . PATH_SEPARATOR . '/path/to/lib' . DIRECTORY_SEPARATOR);spl_autoload_register(); // 使用內置 spl_autoloadspl_autoload_register('myAutoloader');function myAutoloader($class) {
// PSR-4 風格:命名空間映射目錄
$prefix = 'App\\';
if (strncmp($class, $prefix, strlen($prefix)) !== 0) return;
$relative = substr($class, strlen($prefix));
$file = __DIR__ . '/src/' . str_replace('\\', '/', $relative) . '.php';
if (is_file($file)) require $file;
}
spl_autoload_register('myAutoloader');
__autoload 會在 SPL 棧之前執行,建議完全遷移到 SPL。spl_autoload_unregister('myAutoloader');vendor/autoload.php(內部即使用 SPL)更為標準。