I'm trying to access a class constant in one of my classes:
const MY_CONST = "value";
If I have a variable to hold the name of this constant like this:
$myVar = "MY_CONST";
Can I access the value of MY_CONST somehow?
self::$myVar
This obviously doesn't work since it's for a static property. Also, variable variables don't work either.
P粉4045397322023-10-21 13:52:00
There is no corresponding syntax, but you can use explicit lookup:
print constant("classname::$myConst");
I believe it also works with self::
.
P粉1037395662023-10-21 13:02:38
There are two ways to do this: using a constant function or using reflection.
Constant functions apply to constants declared via define
as well as class constants:
class A { const MY_CONST = 'myval'; static function test() { $c = 'MY_CONST'; return constant('self::'. $c); } } echo A::test(); // output: myval
The second, more laborious method is through reflection:
$ref = new ReflectionClass('A'); $constName = 'MY_CONST'; echo $ref->getConstant($constName); // output: myval