PHP Reflection API 允許執行時檢查類別結構。ReflectionClass 可取得常數、方法、屬性、介面等中繼資料,適用於框架開發、自動載入、文件產生等場景。
class MyTestClass {
const TESTVAR1 = 1001;
const TESTVAR2 = 1002;
const TESTSTR1 = 'hello';
}
$rc = new ReflectionClass('MyTestClass');
$constants = $rc->getConstants();
asort($constants); // 依值排序;ksort() 依鍵排序
foreach ($constants as $name => $value) {
echo "$name => $value\n";
}
/* 輸出:
TESTSTR1 => hello
TESTVAR1 => 1001
TESTVAR2 => 1002
*/
getMethods():取得所有方法(含繼承)getProperties():取得所有屬性getInterfaces():實作的介面getParentClass():父類別isInstantiable():是否可實例化hasMethod($name) / hasProperty($name) / hasConstant($name):存在性檢查結合 ReflectionMethod、ReflectionProperty 可進一步取得參數、修飾詞、註解等資訊,構建強大的元編程工具。