Accessing a class constant using a simple variable which contains the name of the constant

There are two ways to do this: using the constant function or using reflection.

Constant Function

The constant function works with constants declared through 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

Reflection Class

A second, more laborious way, would be through reflection:

$ref = new ReflectionClass('A');
$constName="MY_CONST";
echo $ref->getConstant($constName); // output: myval

Leave a Comment