PHP 反射 API (ReflectionClass, ReflectionMethod, ReflectionFunction, ReflectionParameter) 讓代碼能在運行時檢查、修改自身結構。本文通過三個實戰場景——**定位定義位置、自動路由掃描、簡易依賴注入容器**——深度講解反射核心用法與性能考量。
| 類 | 用途 | 常用方法 |
|---|---|---|
ReflectionClass | 類/接口/Trait 信息 | getName(), getFileName(), getStartLine(), getMethods(), getProperties(), getConstructor(), newInstanceArgs(), getAttributes() (PHP 8) |
ReflectionMethod | 方法信息 | getName(), getParameters(), getReturnType(), isPublic(), invoke(), invokeArgs() |
ReflectionFunction | 函數/閉包信息 | getParameters(), getReturnType(), invoke(), invokeArgs() |
ReflectionParameter | 參數信息 | getName(), getType(), isOptional(), getDefaultValue(), getAttributes() |
ReflectionProperty | 屬性信息 | getName(), getType(), getValue($obj), setValue($obj, $val), setAccessible(true) |
ReflectionAttribute | PHP 8 屬性 (註解) | getName(), getArguments(), newInstance() |
<?php
function getDefinitionPosition(string $name): array
{
$info = [];
// 1. 檢查類
if (class_exists($name) || interface_exists($name) || trait_exists($name)) {
$rc = new ReflectionClass($name);
$info['class'] = [
'file' => $rc->getFileName(),
'start_line' => $rc->getStartLine(),
'end_line' => $rc->getEndLine(),
'namespace' => $rc->getNamespaceName(),
'modifiers' => Reflection::getModifierNames($rc->getModifiers()),
];
}
// 2. 檢查函數
if (function_exists($name)) {
$rf = new ReflectionFunction($name);
$info['function'] = [
'file' => $rf->getFileName(),
'start_line' => $rf->getStartLine(),
'end_line' => $rf->getEndLine(),
'namespace' => $rf->getNamespaceName(),
'parameters' => array_map(fn($p) => [
'name' => $p->getName(),
'type' => $p->getType()?->getName(),
'optional' => $p->isOptional(),
'default' => $p->isOptional() ? $p->getDefaultValue() : null,
], $rf->getParameters()),
];
}
return $info;
}
// 使用
print_r(getDefinitionPosition('App\\Controller\\UserController'));
print_r(getDefinitionPosition('helper_function'));
掃描控制器目錄,讀取方法上的 #[Route] 屬性 (PHP 8) 或 DocBlock 註解 (PHP 7),自動構建路由表。
<?php
#[\Attribute(Attribute::TARGET_METHOD)]
class Route
{
public function __construct(
public string $path,
public array $methods = ['GET'],
public string $name = '',
public array $middleware = [],
) {}
}
// 控制器示例
class UserController
{
#[Route('/users', methods: ['GET'], name: 'users.index')]
public function index() { /* ... */ }
#[Route('/users/{id}', methods: ['GET'], name: 'users.show')]
public function show(int $id) { /* ... */ }
#[Route('/users', methods: ['POST'], name: 'users.store', middleware: ['auth', 'throttle'])]
public function store(Request $request) { /* ... */ }
}
// 路由掃描器
class RouteScanner
{
public function scan(string $controllerDir, string $namespace): array
{
$routes = [];
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($controllerDir, FilesystemIterator::SKIP_DOTS)
);
foreach ($files as $file) {
if ($file->getExtension() !== 'php') continue;
$className = $namespace . '\\' . str_replace(['/', '.php'], ['\\', ''],
substr($file->getPathname(), strlen($controllerDir) + 1));
if (!class_exists($className)) continue;
$rc = new ReflectionClass($className);
if ($rc->isAbstract() || !$rc->isInstantiable()) continue;
foreach ($rc->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
$attrs = $method->getAttributes(Route::class);
foreach ($attrs as $attr) {
/** @var Route $route */
$route = $attr->newInstance();
$routes[] = [
'path' => $route->path,
'methods' => $route->methods,
'handler' => [$className, $method->getName()],
'name' => $route->name ?: $method->getName(),
'middleware' => $route->middleware,
'parameters' => $this->getMethodParameters($method),
];
}
}
}
return $routes;
}
private function getMethodParameters(ReflectionMethod $method): array
{
$params = [];
foreach ($method->getParameters() as $param) {
$params[] = [
'name' => $param->getName(),
'type' => $param->getType()?->getName(),
'optional' => $param->isOptional(),
'default' => $param->isOptional() ? $param->getDefaultValue() : null,
];
}
return $params;
}
}
// 使用
$scanner = new RouteScanner();
$routes = $scanner->scan(__DIR__ . '/../Controller', 'App\\Controller');
// 註冊到路由器...
/**
* @Route("/users", methods={"GET"}, name="users.index")
*/
public function index() { }
// 解析
$docComment = $method->getDocComment();
if (preg_match('/@Route\s*\((.*?)\)/s', $docComment, $matches)) {
// 解析參數字符串... (建議用 doctrine/annotations 庫)
}
核心原理:反射構造函數參數 → 遞歸解析依賴 → 實例化注入。
<?php
class Container
{
private array $bindings = []; // 類名 -> 實例/工廠/單例
private array $singletons = []; // 單例實例緩存
private array $resolving = []; // 循環依賴檢測
/** 綁定接口到實現 */
public function bind(string $abstract, $concrete = null, bool $singleton = false): void
{
$this->bindings[$abstract] = ['concrete' => $concrete ?? $abstract, 'singleton' => $singleton];
}
/** 綁定單例 */
public function singleton(string $abstract, $concrete = null): void
{
$this->bind($abstract, $concrete, true);
}
/** 實例化 */
public function make(string $abstract, array $parameters = [])
{
// 1. 檢查單例緩存
if (isset($this->singletons[$abstract])) {
return $this->singletons[$abstract];
}
// 2. 循環依賴檢測
if (isset($this->resolving[$abstract])) {
throw new \RuntimeException("Circular dependency detected for {$abstract}");
}
$this->resolving[$abstract] = true;
// 3. 獲取具體類
$binding = $this->bindings[$abstract] ?? ['concrete' => $abstract, 'singleton' => false];
$concrete = $binding['concrete'];
// 4. 如果是閉包工廠
if ($concrete instanceof \Closure) {
$instance = $concrete($this, $parameters);
} else {
// 5. 反射構造函數自動注入
$instance = $this->resolveClass($concrete, $parameters);
}
// 6. 單例緩存
if ($binding['singleton']) {
$this->singletons[$abstract] = $instance;
}
unset($this->resolving[$abstract]);
return $instance;
}
private function resolveClass(string $class, array $parameters = [])
{
$rc = new ReflectionClass($class);
if (!$rc->isInstantiable()) {
throw new \RuntimeException("Class {$class} not instantiable");
}
$constructor = $rc->getConstructor();
if (!$constructor) {
return new $class();
}
$deps = [];
foreach ($constructor->getParameters() as $param) {
$name = $param->getName();
// 顯式傳參優先
if (array_key_exists($name, $parameters)) {
$deps[] = $parameters[$name];
continue;
}
// 類型提示自動注入
$type = $param->getType();
if ($type && !$type->isBuiltin()) {
$typeName = $type->getName();
$deps[] = $this->make($typeName);
} elseif ($param->isOptional()) {
$deps[] = $param->getDefaultValue();
} else {
throw new \RuntimeException("Cannot resolve parameter {$name} for {$class}");
}
}
return $rc->newInstanceArgs($deps);
}
}
// ========== 使用示例 ==========
$container = new Container();
// 綁定
$container->singleton(PDO::class, fn($c) => new PDO('mysql:host=127.0.0.1;dbname=app', 'user', 'pass'));
$container->bind(LoggerInterface::class, FileLogger::class);
$container->singleton(Config::class);
// 控制器自動注入
class UserController
{
public function __construct(
private PDO $db,
private LoggerInterface $logger,
private Config $config
) {}
public function index() { /* ... */ }
}
// 解析控制器 (路由分發時)
$controller = $container->make(UserController::class);
$controller->index();
new ReflectionClass 都解析文件。生產環境**必須緩存**反射結果(路由表、容器定義)。ReflectionAttribute 比解析 DocBlock 快得多,強烈建議升級 PHP 8 並使用屬性。反射是框架級功能的基石:**路由、DI 容器、ORM 映射、序列化、驗證、測試雙工** 都依賴它。業務代碼極少直接用反射,但理解其原理能讓你深度掌握框架行為、編寫開發工具、實現動態代理/AOP。核心口訣:開發期反射掃描構建元數據 → 緩存元數據 → 運行時零反射高速執行。