SPL 提供的自動加載機制是 Composer、框架核心、插件系統的基礎設施。本文深度解析 spl_autoload_register、spl_autoload、spl_autoload_extensions 的協作原理與生產級用法。
spl_autoload_register() ← 註冊加載器到棧 (LIFO 順序)
│
├── 參數為 callable → 使用自定義加載邏輯
└── 參數為 null → 使用內置 spl_autoload() (依賴 spl_autoload_extensions)
spl_autoload() ← 內置默認實現
│
├── 掃描 include_path
└── 嘗試加載: $class . $ext (擴展名來自 spl_autoload_extensions)
spl_autoload_extensions() ← 設置內置加載器嘗試的擴展名列表
<?php
// 1. 設置可加載的文件擴展名 (優先級順序)
spl_autoload_extensions('.php,.inc.php,.class.php,.lib.php');
// 2. 設置類文件搜索路徑
set_include_path(
get_include_path() . PATH_SEPARATOR . __DIR__ . '/libs/'
. PATH_SEPARATOR . __DIR__ . '/vendor/'
);
// 3. 註冊內置加載器 (無參數調用)
spl_autoload_register();
// 4. 直接使用類,自動觸發加載
$obj1 = new Test1(); // 尋找 Test1.php, Test1.inc.php...
$obj2 = new Test2(); // 尋找 Test2.lib.php...
?>
<?php
// 符合 PSR-4 的自動加載器
class Psr4Autoloader {
private $prefixes = [];
public function addNamespace(string $prefix, string $baseDir): void {
$prefix = rtrim($prefix, '\\') . '\\';
$baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$this->prefixes[$prefix][] = $baseDir;
}
public function loadClass(string $class): void {
foreach ($this->prefixes as $prefix => $dirs) {
if (str_starts_with($class, $prefix)) {
$relativeClass = substr($class, strlen($prefix));
$file = str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';
foreach ($dirs as $dir) {
$fullPath = $dir . $file;
if (file_exists($fullPath)) {
require $fullPath;
return;
}
}
}
}
}
public function register(): void {
spl_autoload_register([$this, 'loadClass']);
}
}
// 使用
$loader = new Psr4Autoloader();
$loader->addNamespace('App', __DIR__ . '/src');
$loader->addNamespace('Vendor\\Package', __DIR__ . '/vendor/package/src');
$loader->register();
// 現在可以直接使用
$user = new App\Entity\User();
$service = new Vendor\Package\Service\ApiClient();
?>
<?php
// 註冊順序決定優先級:後註冊的優先嘗試 (棧頂)
spl_autoload_register('loader1'); // 先註冊,後嘗試
spl_autoload_register('loader2'); // 後註冊,先嘗試
// 查看已註冊加載器
print_r(spl_autoload_functions());
// 移除特定加載器
spl_autoload_unregister('loader1');
// 手動觸發所有加載器嘗試加載
spl_autoload_call('MyClass');
?>
<?php
// vendor/composer/autoload_real.php 核心邏輯簡化版
class ComposerAutoloader {
private $classMap = []; // 類名 -> 文件路徑 (優先級最高)
private $psr4 = []; // 命名空間前綴 -> 目錄列表
private $psr0 = []; // 命名空間前綴 -> 目錄列表 (舊標準)
private $files = []; // 全局函數文件
public function loadClass($class) {
// 1. 類映射表直接查找 (O(1))
if (isset($this->classMap[$class])) {
require $this->classMap[$class];
return true;
}
// 2. PSR-4 映射查找
if ($this->findFileWithPsr4($class)) return true;
// 3. PSR-0 映射查找 (兼容舊庫)
if ($this->findFileWithPsr0($class)) return true;
return false;
}
public function register() {
spl_autoload_register([$this, 'loadClass'], true, true); // prepend=true 優先級最高
}
}
?>
| 函數 | 用途 | 示例 |
|---|---|---|
| iterator_to_array | 迭代器轉數組 | iterator_to_array(new DirectoryIterator('.')) |
| iterator_count | 計算迭代器元素數 | iterator_count(new ArrayIterator([1,2,3])) // 3 |
| iterator_apply | 對每個元素調用回調 | iterator_apply($it, 'func', [$it]) |
| class_parents | 獲取父類鏈 | class_parents('ChildClass') |
| class_implements | 獲取實現的接口 | class_implements('MyClass') |
| class_uses | 獲取使用的 Trait | class_uses('MyClass') |
| spl_object_hash | 對象唯一標識 | spl_object_hash($obj) |
| spl_object_id | 對象整數 ID (PHP 7.2+) | spl_object_id($obj) |
composer dump-autoload -o 生成類映射表,提升加載速度spl_autoload_functions() 排查加載順序問題