PHP Reflection API(PHP 5+)提供運行時檢測類、介面、方法、屬性、參數、擴充等結構信息的能力,是框架開發、依賴注入、註解解析、代碼生成、測試工具的基石。
| 類別 | 用途 |
|---|---|
| ReflectionClass | 類/介面/Trait 檢測 |
| ReflectionMethod | 類方法檢測 |
| ReflectionFunction | 函數/閉包檢測 |
| ReflectionProperty | 類屬性檢測 |
| ReflectionParameter | 函數/方法參數檢測 |
| ReflectionObject | 物件實例檢測(繼承 ReflectionClass) |
| ReflectionExtension | 擴充模組檢測 |
| ReflectionType / ReflectionNamedType | 類型提示檢測 (PHP 7+) |
| ReflectionAttribute | 屬性/註解檢測 (PHP 8+) |
<?php
class User {
private $id;
protected $name;
public $email;
public function __construct($id, $name, $email) {
$this->id = $id; $this->name = $name; $this->email = $email;
}
public function getName() { return $this->name; }
public function setName($name) { $this->name = $name; }
}
$rc = new ReflectionClass('User');
// 基本信息
echo "Class: " . $rc->getName() . "\n";
echo "Namespace: " . $rc->getNamespaceName() . "\n";
echo "File: " . $rc->getFileName() . ":" . $rc->getStartLine() . "\n";
echo "Modifiers: " . implode(', ', Reflection::getModifierNames($rc->getModifiers())) . "\n";
echo "Parent: " . ($rc->getParentClass() ? $rc->getParentClass()->getName() : 'none') . "\n";
echo "Interfaces: " . implode(', ', $rc->getInterfaceNames()) . "\n";
echo "Traits: " . implode(', ', $rc->getTraitNames()) . "\n";
echo "Constants: " . print_r($rc->getConstants(), true);
echo "Static Props: " . print_r($rc->getStaticProperties(), true);
// 屬性檢測(含私有)
foreach ($rc->getProperties(ReflectionProperty::IS_PRIVATE) as $prop) {
$prop->setAccessible(true); // 關鍵:訪問私有屬性
echo "Private prop: {$prop->getName()} = " . $prop->getValue($user) . "\n";
}
// 方法檢測
foreach ($rc->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
echo "Method: {$method->getName()}()\n";
echo " DocComment: " . $method->getDocComment() . "\n";
echo " Params: ";
foreach ($method->getParameters() as $param) {
echo "{$param->getName()}" . ($param->isOptional() ? ' = ' . var_export($param->getDefaultValue(), true) : '') . ", ";
}
echo "\n";
}
<?php
$rc = new ReflectionClass('User');
// newInstanceArgs 自動匹配建構子參數
$user = $rc->newInstanceArgs(array(1, 'John', 'john@example.com'));
// 動態調用方法
$method = $rc->getMethod('setName');
$method->invoke($user, 'Jane'); // $user->setName('Jane')
// 靜態方法調用
$method->invoke(null, 'Static Call'); // 若為 static
<?php
function process(string $name, int $age = 18, ArrayObject $data = null): bool {
return true;
}
$rf = new ReflectionFunction('process');
foreach ($rf->getParameters() as $param) {
echo "Param: {$param->getName()}\n";
echo " Type: " . ($param->getType() ? $param->getType()->getName() : 'none') . "\n";
echo " Optional: " . ($param->isOptional() ? 'yes' : 'no') . "\n";
echo " Default: " . var_export($param->getDefaultValue(), true) . "\n";
echo " AllowsNull: " . ($param->allowsNull() ? 'yes' : 'no') . "\n";
echo " PassedByRef: " . ($param->isPassedByReference() ? 'yes' : 'no') . "\n";
// PHP 8 Attributes
foreach ($param->getAttributes() as $attr) {
echo " Attribute: " . $attr->getName() . "\n";
}
}
<?php
$re = new ReflectionExtension('json');
echo "Version: " . $re->getVersion() . "\n";
echo "Functions: " . implode(', ', array_keys($re->getFunctions())) . "\n";
echo "Constants: " . print_r($re->getConstants(), true);
echo "INI Entries: " . print_r($re->getINIEntries(), true);
echo "Dependencies: " . print_r($re->getDependencies(), true);
<?php
class Container {
private $bindings = array();
public function bind($abstract, $concrete = null) {
$this->bindings[$abstract] = $concrete ?: $abstract;
}
public function make($abstract) {
if (!isset($this->bindings[$abstract])) {
throw new Exception("Binding not found: $abstract");
}
$concrete = $this->bindings[$abstract];
$rc = new ReflectionClass($concrete);
if (!$rc->isInstantiable()) {
throw new Exception("Not instantiable: $concrete");
}
$constructor = $rc->getConstructor();
if (!$constructor) {
return $rc->newInstance();
}
$params = $constructor->getParameters();
$args = array();
foreach ($params as $param) {
$type = $param->getType();
if ($type && !$type->isBuiltin()) {
$typeName = $type->getName();
$args[] = $this->make($typeName); // 遞迴解析依賴
} elseif ($param->isOptional()) {
$args[] = $param->getDefaultValue();
} else {
throw new Exception("Cannot resolve parameter: {$param->getName()}");
}
}
return $rc->newInstanceArgs($args);
}
}
// 使用
$container = new Container();
$container->bind('db', 'PDO'); // 假設 PDO 有對應建構子
$container->bind('UserRepository', 'MySQLUserRepository');
$userRepo = $container->make('UserRepository');
$rc = new ReflectionClass($class); 緩存實例Reflection API 賦予 PHP 動態語言的極致靈活性,善用它能構建極具擴展性的系統架構。