PHP 5 引入完整的 Reflection API,讓開發者能在執行期動態檢查類別、介面、函式、方法與擴充套件的結構資訊,甚至讀取文件註解。這為框架開發、依賴注入、自動載入等進階應用奠定基礎。
| 類別 | 用途 |
|---|---|
ReflectionClass | 檢視類別結構:屬性、方法、常數、介面、命名空間等 |
ReflectionProperty | 取得屬性可見度、靜態、預設值、文件註解 |
ReflectionMethod | 分析方法簽名、參數、存取修飾子、呼叫 invoke() 動態執行 |
ReflectionFunction | 對應函式/閉包,支援參數綁定與動態呼叫 |
<?php
class Foo {
public $foo = 1;
protected $bar = 2;
private $baz = 3;
/** 範例方法文件註解 */
public function myMethod() {
echo 'hello world';
}
}
$ref = new ReflectionClass('Foo');
// 1. 列出所有屬性(含 private/protected)
foreach ($ref->getProperties() as $prop) {
echo $prop->getName() . PHP_EOL;
}
// 輸出:foo, bar, baz
// 2. 取得特定方法並動態呼叫
$method = $ref->getMethod('myMethod');
$instance = $ref->newInstance();
$method->invoke($instance); // 輸出:hello world
?>
許多 PHP 框架(Kohana、Yii、Laravel 早期版本)利用反射實現控制器自動實例化與動作分派:
<?php // 簡化版分派器邏輯 $controllerClass = ucfirst(Router::$controller) . '_Controller'; $ref = new ReflectionClass($controllerClass); $controller = $ref->newInstance(); $actionMethod = $ref->getMethod(Router::$method); $actionMethod->invokeArgs($controller, $arguments); ?>
此模式解耦了路由解析與控制器實例化,支援外掛式架構擴充。
<?php
class User {
/** @Column(type="integer", primary=true) */
public $id;
/** @Column(type="string", length=100) */
public $name;
}
$ref = new ReflectionClass('User');
foreach ($ref->getProperties() as $prop) {
$doc = $prop->getDocComment();
// 解析 @Column 註解建立 ORM 映射
}
?>
ReflectionClass 實例。opcache 減少重複解析開銷。掌握 Reflection API,能讓你編寫更靈活、可擴充的 PHP 程式庫與框架核心元件。