萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP Reflection API 完整指南:類、方法、屬性、參數運行時檢測

Reflection 簡介

PHP Reflection API(PHP 5+)提供運行時檢測類、介面、方法、屬性、參數、擴充等結構信息的能力,是框架開發、依賴注入、註解解析、代碼生成、測試工具的基石。

核心類別體系

類別用途
ReflectionClass類/介面/Trait 檢測
ReflectionMethod類方法檢測
ReflectionFunction函數/閉包檢測
ReflectionProperty類屬性檢測
ReflectionParameter函數/方法參數檢測
ReflectionObject物件實例檢測(繼承 ReflectionClass)
ReflectionExtension擴充模組檢測
ReflectionType / ReflectionNamedType類型提示檢測 (PHP 7+)
ReflectionAttribute屬性/註解檢測 (PHP 8+)

常用操作範例

1. 類結構檢測

<?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";
}

2. 動態實例化與調用

<?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

3. 參數類型與屬性檢測 (PHP 8+)

<?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";
    }
}

4. 擴充模組檢測

<?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);

5. 實戰:簡易依賴注入容器

<?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');

性能考量

  • Reflection 操作較慢(解析結構、字串操作),避免在熱點路徑頻繁調用
  • 緩存 Reflection 結果:$rc = new ReflectionClass($class); 緩存實例
  • 生產環境配合 OPcache,類結構緩存可減輕開銷
  • PHP 8.0+ 內部優化,Reflection 性能顯著提升

最佳實踐

  1. 框架開發:路由、控制器解析、中間件、驗證器
  2. ORM/ODM:實體映射、關係解析、遷移生成
  3. 測試工具:Mock 框架、數據提供者、測試雙
  4. 文檔生成:API 文檔自動生成(Swagger/OpenAPI)
  5. 代碼生成:DTO、Repository、Factory 樣板代碼
  6. 插件系統:動態載入、能力檢測、生命週期鉤子

Reflection API 賦予 PHP 動態語言的極致靈活性,善用它能構建極具擴展性的系統架構。

copyright © 萬盛學電腦網 all rights reserved