首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP ReflectionClass 遍歷類別常數:靜態分析與動態取值實戰

     編輯:PHP 綜合知識

需求:取得類別所有 const 定義,以鍵值對形式輸出,支援排序。

核心程式碼

<?php
class MyTestClass {
    const TESTVAR1 = 1001;
    const TESTVAR2 = 1002;
    const TESTSTR1 = 'hello';
}

$rc = new ReflectionClass('MyTestClass');
$constants = $rc->getConstants(); // ['TESTVAR1'=>1001, 'TESTVAR2'=>1002, 'TESTSTR1'=>'hello']

// 依值排序
asort($constants);
// 依鍵排序
// ksort($constants);

foreach ($constants as $name => $value) {
    echo "$name => $value\n";
}

輸出結果

TESTSTR1 => hello
TESTVAR1 => 1001
TESTVAR2 => 1002

擴展:取得方法、屬性、介面、父類等

需求ReflectionClass 方法回傳型別
所有常數getConstants()array
單一常數getConstant('NAME')mixed
所有方法getMethods()ReflectionMethod[]
所有屬性getProperties()ReflectionProperty[]
實作介面getInterfaces()ReflectionClass[]
父類別getParentClass()ReflectionClass|null
類別註解getDocComment()string|false

進階:過濾屬性可視性

<?php
$rc = new ReflectionClass('MyClass');

// 僅 public 屬性
$pubProps = $rc->getProperties(ReflectionProperty::IS_PUBLIC);

// 僅 private 方法
$privMethods = $rc->getMethods(ReflectionMethod::IS_PRIVATE);

實戰場景

  • 自動化 API 文檔生成:掃描 Controller 類別、方法註解、參數型別,產出 OpenAPI/Swagger JSON。
  • 配置驗證:讀取 Config 類別常數,對比資料庫/環境變數,啟動時檢查一致性。
  • 依賴注入容器掃描:分析建構子參數型別提示,自動解析依賴圖。
  • 單元測試資料提供者:反射測試類別 @dataProvider 方法,動態組裝測試資料。

效能提示

  • Reflection 操作涉及內部結構遍歷,**較慢**,避免在高頻熱路徑(如每請求)大量使用。
  • 啟動階段掃描並快取結果(如 Composer 自動載入優化、框架啟動暖機),運行期直接讀快取。
  • PHP 8.0+ 可搭配 #[Attribute] 替代註解,反射讀取 Attribute 比解析 DocComment 快數倍。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved