[英]Get the defining class for a constant in PHP
我想使用反射來獲取由 PHP 中的類定義的常量列表。
目前使用反射我可以獲得常量列表,但這也包括在繼承類中聲明的常量。 有沒有我可以使用的方法?
例如,在下面的代碼中:
class Foo {
const PARENT_CONST = 'parent';
const ANOTHER_PARENT_CONST = 'another_parent';
}
class Bar extends Foo {
const CHILD_CONST = 'child';
const BAR_CONST = 'bar_const';
}
$reflection = new ReflectionClass('Bar');
print_r($reflection->getConstants());
輸出是:
Array
(
[CHILD_CONST] => child
[BAR_CONST] => bar_const
[PARENT_CONST] => parent
[ANOTHER_PARENT_CONST] => another_parent
)
但我只想擁有這個:
Array
(
[CHILD_CONST] => child
[BAR_CONST] => bar_const
)
默認情況下,據我所知,PHP 沒有已經刪除父類和接口常量的函數。 所以你需要自己做:
$reflection = new ReflectionClass('Bar');
$buffer = $reflection->getConstants();
foreach (
array($reflection->getParentClass())
+ $reflection->getInterfaces()
as $fill
) {
$buffer = array_diff_key($buffer, $fill->getConstants());
}
$buffer
中的結果就是你要查找的數組:
Array
(
[CHILD_CONST] => child
[BAR_CONST] => bar_const
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.