萬盛學電腦網

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

PHP 反射類 ReflectionClass 完整指南與實戰模式

什麼是 ReflectionClass?

ReflectionClass 是 PHP 內建的反射 API 核心類,能在運行時「掃描」類的結構:屬性、方法、常量、接口、繼承關係、註解等,並支持動態實例化、調用方法、讀寫屬性。適用於框架開發、依賴注入、插件系統、自動化測試等場景。

基礎示例

class Foo {
    public static function bar() {
        echo 'Hello Reflection!';
    }
}

// 建立反射類
$rc = new ReflectionClass('Foo');

// 輸出類結構摘要
echo $rc; 
/* 輸出示例:
Class [ class Foo ] {
  - Methods [1] {
    Method [ public static method bar ] { ... }
  }
}
*/

// 動態實例化(等同 new Foo())
$instance = $rc->newInstance();

// 獲取方法反射對象並調用
$method = $rc->getMethod('bar');
$method->invoke($instance); // 輸出:Hello Reflection!

進階用法:框架控制器調度(典型 MVC 模式)

try {
    $controllerName = $this->getController(); // 如 'UserController'
    $actionName     = $this->getAction();     // 如 'login'

    if (!class_exists($controllerName)) {
        throw new Exception('Controller not found');
    }

    $rc = new ReflectionClass($controllerName);

    // 1. 檢查是否實現了規定接口
    if (!$rc->implementsInterface('IController')) {
        throw new Exception('Interface IController required');
    }

    // 2. 檢查 Action 方法是否存在
    if (!$rc->hasMethod($actionName)) {
        throw new Exception('Action not found');
    }

    // 3. 實例化控制器
    $controller = $rc->newInstance();

    // 4. 獲取方法反射並調用(支持參數綁定)
    $method = $rc->getMethod($actionName);
    $method->invoke($controller); // 也可用 invokeArgs($controller, $params)

} catch (Exception $e) {
    // 統一異常處理:404、500、日誌記錄等
    echo $e->getMessage();
}

核心 API 速查表

方法用途
getName()獲取類名(含命名空間)
getNamespaceName()獲取命名空間
getParentClass()獲取父類反射對象
implementsInterface($name)判斷是否實現某接口
isAbstract() / isFinal() / isInterface() / isTrait()類型判斷
getProperties() / getProperty($name)獲取所有/單個屬性反射
getMethods() / getMethod($name)獲取所有/單個方法反射
getConstants() / getConstant($name)獲取常量
getDocComment()獲取類/方法/屬性的 DocBlock 註解
newInstance($args...)實例化(構造函數有參數時傳參)
newInstanceWithoutConstructor()不調用構造函數創建實例(慎用)
getFileName() / getStartLine() / getEndLine()源文件路徑與行號

性能提示

  • 反射涉及運行時解析,**比直接調用慢 10~100 倍**,請避免在高頻熱點路徑(如每請求循環)使用。
  • 框架通常在**啟動/路由解析階段**做反射掃描,並將結果**緩存**(如存入 APCu/Redis/文件),運行期直接讀取緩存。

總結

ReflectionClass 是 PHP 元編程的基石,掌握它能讓你編寫更靈活、解耦的框架級代碼。記住:開發期反射、運行期緩存,兼得靈活與性能。

copyright © 萬盛學電腦網 all rights reserved