自動載入相關函數
spl_autoload_extensions():設定預設副檔名
<?php
// 設定 spl_autoload() 可載入的副檔名 (預設 .inc, .php)
spl_autoload_extensions('.php,.class.php,.lib.php');
spl_autoload_register():註冊自動載入器 (推薦)
<?php
// 1. 使用預設 spl_autoload() (依據 spl_autoload_extensions + include_path)
spl_autoload_register();
// 2. 註冊自訂載入器 (PSR-4 風格)
spl_autoload_register(function (string $class) {
$file = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
require $file;
}
});
// 3. 註冊類別靜態方法
spl_autoload_register([MyLoader::class, 'load']);
// 4. 註冊物件方法
$loader = new MyLoader();
spl_autoload_register([$loader, 'load']);
完整範例:多副檔名 + 多路徑
<?php
/* 目錄結構:
/project
/libs
Test2.lib.php
test1.php
test.php
*/
// test1.php
class Test1 {}
// libs/Test2.lib.php
class Test2 {}
// test.php
spl_autoload_extensions('.php,.lib.php');
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/libs');
spl_autoload_register(); // 使用預設 spl_autoload()
$t1 = new Test1(); // 載入 test1.php
$t2 = new Test2(); // 載入 libs/Test2.lib.php
spl_autoload():預設實現
<?php
// 手動觸發預設自動載入
spl_autoload('Test1'); // 會在 include_path 尋找 Test1.php / Test1.inc
$obj = new Test1();
spl_autoload_call():嘗試所有已註冊載入器
<?php
function myLoader(string $class): void {
if ($class === 'Test1') require __DIR__ . '/test1.php';
if ($class === 'Test2') require __DIR__ . '/test2.lib.php';
}
spl_autoload_register('myLoader');
spl_autoload_call('Test2'); // 觸發載入
$obj = new Test(); // 來自 test2.lib.php
$obj->getFilename(); // test2.lib.php
其他自動載入輔助函數
| 函數 | 用途 |
| spl_autoload_functions() | 返回所有已註冊的自動載入器陣列 |
| spl_autoload_unregister() | 移除已註冊的自動載入器 |
迭代器工具函數
<?php
$iterator = new ArrayIterator(['recipe' => 'pancakes', 'egg', 'milk', 'flour']);
// 迭代器 → 陣列
$array = iterator_to_array($iterator);
print_r($array);
// 計算元素數量
echo "Count: " . iterator_count($iterator) . "\n"; // 4
// 為每個元素呼叫自訂函數
iterator_apply($iterator, 'printItem', [$iterator]);
function printItem(Iterator $it): bool {
echo strtoupper($it->current()) . "\n";
return true; // 必須返回 true 繼續迭代
}
/* 輸出:
PANCAKES
EGG
MILK
FLOUR
*/
類別結構檢查函數
<?php
interface Loggable {}
trait Timestampable {}
class Base {}
class Child extends Base implements Loggable {
use Timestampable;
}
// 取得實現的介面
print_r(class_implements(Child::class)); // [Loggable => Loggable]
// 取得父類別
print_r(class_parents(Child::class)); // [Base => Base]
// 取得使用的 Trait (PHP 7.0+)
print_r(class_uses(Child::class)); // [Timestampable => Timestampable]
// 取得所有可用 SPL 類別
print_r(spl_classes());
// 物件唯一識別碼 (同一物件在同一請求中固定)
$obj = new stdClass();
echo spl_object_hash($obj); // 如: 000000003a1b2c3d...
實戰建議
- 自動載入:現代專案請直接使用 Composer PSR-4,無需手寫
spl_autoload_register。Composer 生成的 vendor/autoload.php 內部即使用 SPL 自動載入機制。
- 迭代器轉陣列:
iterator_to_array 記憶體消耗大,大資料集請直接遍歷迭代器或使用 Generator。
- spl_object_hash:用於物件身分識別、快取鍵值、避免重複處理同一物件。
- class_* 系列:適用於框架開發、註解掃描、依賴注入容器建構等元編程場景。