
Question:
Is it possible to access the value of a class constant dynamically using a variable that contains the constant's name?
Answer:
Yes, there are two methods to achieve this: using the constant function or reflection.
Method 1: Constant Function
The constant function can be used to retrieve the value of both user-defined constants declared with define and class constants:
<code class="php">class A
{
const MY_CONST = 'myval';
static function test()
{
$c = 'MY_CONST';
return constant('self::'. $c);
}
}
echo A::test(); // outputs "myval"</code>Method 2: Reflection Class
A more comprehensive approach is to use reflection:
<code class="php">$ref = new ReflectionClass('A');
$constName = 'MY_CONST';
echo $ref->getConstant($constName); // outputs "myval"</code>The above is the detailed content of Can I Access Class Constant Values Dynamically Using a Variable?. For more information, please follow other related articles on the PHP Chinese website!