函數(shù):ReflectionClass::getConstant()
適用版本:PHP 5 >= 5.1.0, PHP 7
用法:ReflectionClass::getConstant() 方法用于獲取指定類的常量值。
語法:public ReflectionClass::getConstant(string $name): mixed
參數(shù):
- $name:要獲取的常量名稱。
返回值:獲取到的常量值,如果常量不存在則返回 NULL。
示例:
class MyClass {
const MY_CONSTANT = 123;
}
$reflection = new ReflectionClass('MyClass');
$constantValue = $reflection->getConstant('MY_CONSTANT');
var_dump($constantValue); // 輸出 int(123)
在上面的示例中,我們首先定義了一個名為MyClass
的類,并在該類中定義了一個常量MY_CONSTANT
,其值為123。
然后,我們使用ReflectionClass
類創(chuàng)建了一個反射對象$reflection
,并將MyClass
作為參數(shù)傳遞給它。
接下來,我們使用$reflection
對象的getConstant()
方法來獲取MyClass
類中名為MY_CONSTANT
的常量的值,并將其賦值給$constantValue
變量。
最后,我們使用var_dump()
函數(shù)輸出了$constantValue
的值,結(jié)果為int(123)
,表示成功獲取到了常量的值。
請注意,getConstant()
方法只能用于獲取類的常量值,而不能用于獲取類的屬性值或方法。