search

Home  >  Q&A  >  body text

Access class constants using a simple variable containing the constant name

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粉691461301P粉691461301401 days ago588

reply all(2)I'll reply

  • P粉404539732

    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::.

    reply
    0
  • P粉103739566

    P粉1037395662023-10-21 13:02:38

    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

    reply
    0
  • Cancelreply