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.
There is no corresponding syntax, but you can use explicit lookup:
print constant("classname::$myConst");I believe it also works with
self::.There are two ways to do this: using a constant function or using reflection.
Constant function
Constant functions apply to constants declared via
defineas well as class constants:class A { const MY_CONST = 'myval'; static function test() { $c = 'MY_CONST'; return constant('self::'. $c); } } echo A::test(); // output: myvalReflection class
The second, more laborious method is through reflection:
$ref = new ReflectionClass('A'); $constName = 'MY_CONST'; echo $ref->getConstant($constName); // output: myval