需求:取得類別所有 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);
@dataProvider 方法,動態組裝測試資料。#[Attribute] 替代註解,反射讀取 Attribute 比解析 DocComment 快數倍。