Access class constants using a simple variable containing the constant name
P粉691461301
P粉691461301 2023-10-20 14:57:01
0
2
574

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粉691461301
P粉691461301

reply all(2)
P粉404539732

There is no corresponding syntax, but you can use explicit lookup:

print constant("classname::$myConst");

I believe it also works with self::.

P粉103739566

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

Constant function

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

Reflection class

The second, more laborious method is through reflection:

$ref = new ReflectionClass('A');
$constName = 'MY_CONST';
echo $ref->getConstant($constName); // output: myval
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template