我正在嘗試存取我的一個類別中的類別常數(shù):
const MY_CONST = "value";
如果我有一個變數(shù)來保存這個常數(shù)的名稱,如下所示:
$myVar = "MY_CONST";
我可以以某種方式存取 MY_CONST 的值嗎?
self::$myVar
這顯然不起作用,因為它是針對靜態(tài)屬性的。 另外,變數(shù)變數(shù)也不起作用。
沒有對應(yīng)的語法,但您可以使用明確查找:
print constant("classname::$myConst");
我相信它也適用於 self::
。
有兩種方法可以做到這一點:使用 constant 函數(shù)或使用反射。
常數(shù)函數(shù)適用於透過 define
宣告的常數(shù)以及類別常數(shù):
class A { const MY_CONST = 'myval'; static function test() { $c = 'MY_CONST'; return constant('self::'. $c); } } echo A::test(); // output: myval
第二種更費力的方法是透過反射:
$ref = new ReflectionClass('A'); $constName = 'MY_CONST'; echo $ref->getConstant($constName); // output: myval