| 特性 | __autoload() | spl_autoload_register() |
|---|---|---|
| PHP 版本 | PHP 5.0+ | PHP 5.1.2+ |
| 註冊數量 | 全局僅一個 | 支持多個,形成調用棧 |
| 彈性 | 無法協作第三方庫 | 可註冊類方法、閉包、多加載器 |
| 異常處理 | 不支持 | 支持在加載器中拋出異常 |
| 推薦程度 | 已棄用 | 標準做法 |
function __autoload($class) {
$file = $class . '.php';
if (is_file($file)) require_once $file;
}
$a = new A(); // 自動載入 A.php
缺點:項目引入第三方庫時,雙方各自的 __autoload 會衝突覆蓋。
function myLoader($class) {
$file = __DIR__ . '/lib/' . $class . '.php';
if (is_file($file)) require_once $file;
}
spl_autoload_register('myLoader');
class Loader {
public static function load($class) {
$file = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
if (is_file($file)) require_once $file;
}
}
spl_autoload_register(['Loader', 'load']);
// 或 PHP 5.4+ 閉包寫法
spl_autoload_register(function($class) {
$file = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
if (is_file($file)) require_once $file;
});
// 項目自有加載器
spl_autoload_register(['App\Loader', 'load']);
// Composer 加載器(內部已註冊)
require_once __DIR__ . '/vendor/autoload.php';
// 第三方庫加載器
spl_autoload_register(['ThirdLib\Loader', 'load']);
// 調用順序:按註冊順序依次嘗試,直到某加載器成功載入類
spl_autoload():默認實現,按 include_path 查找 類名.inc / 類名.phpspl_autoload_call():遍歷註冊棧調用各加載器spl_autoload_functions():獲取當前註冊的所有加載器spl_autoload_unregister():移除指定加載器// composer.json
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
// 執行 composer dump-autoload 生成 vendor/autoload.php
// 入口文件僅需:
require_once __DIR__ . '/vendor/autoload.php';
Composer 內部使用 spl_autoload_register 註冊高性能映射表查找,支援類別映射、PSR-0/4、文件包含四種策略,生產環境建議 composer dump-autoload -o 生成優化映射。
__autoload 定義spl_autoload_register 並按命名空間拆分加載器require/include,享受零配置加載