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

41,018

Solution 1

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

Solution 2

There is no syntax for that, but you can use an explicit lookup:

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

I believe it also works with self::.

Solution 3

Can I access the value of MY_CONST somehow?

self::MY_CONST

If you want to access is dynamically, you can use the reflection API Docs:

$myvar = 'MY_CONST';
$class = new ReflectionClass(self);
$const = $class->getConstant($myVar);

The benefit with the reflection API can be that you can get all constants at once (getConstants).

If you dislike the reflection API because you don't wanna use it, an alternative is the constant function (Demo):

$myvar = 'MY_CONST';    
class foo {const MY_CONST = 'bar';}    
define('self', 'foo');    
echo constant(self.'::'.$myvar);

Solution 4

Just a note for Reflection: the constructor for ReflectionClass must receive the full path of the class for its parameter. This means that just setting the string 'A' as a constructor parameter may not work in some cases.

To avoid this problem, when using ReflectionClass you will be better if you do this:

$classA = new A();
$name_classA = get_class($classA);
$ref = new ReflectionClass(get_class($name_classA));
$constName = 'MY_CONST';
echo $ref->getConstant($constName);

Function get_class will give you the full path of a class whenever you are in the code. Missing the full path may result in a "Class not found" PHP error.

Solution 5

have you tried

$myVar = MY_CONST or $myVar = $MY_CONST
Share:
41,018
Adam Arold
Author by

Adam Arold

I do programming for a living. I like tinkering with stuff from bare metal to designing architectures. I also contribute to the Open Source community. Currently I'm based on the JVM (Kotlin/Clojure/Java) but I'm still looking for an Elixir (pun intended). Currently I'm hacking simulation-based games and world/flora/fauna/civilization generation (Dwarf Fortress style). If you think we can work together (programming/pixel art) drop me a mail. Check out my Hexagonal Grid library if interested: Hexameter If you need a multiplatform messaging bus: Riptide or a multiplatform terminal emulator for games: Zircon You can find my LinkedIn profile here I also created the unicorns tag on meta and #SOreadytohelp.

Updated on July 05, 2022

Comments

  • Adam Arold
    Adam Arold almost 2 years

    I'm trying to access a class constant in one of my classes:

    const MY_CONST = "value";
    

    If I have a variable which holds the name of this constant like this:

    $myVar = "MY_CONST";
    

    Can I access the value of MY_CONST somehow?

    self::$myVar
    

    does not work obviously because it is for static properties. Variable variables does not work either.

  • Adam Arold
    Adam Arold over 12 years
    I don't know which constant I will be accessing. The name of a constant is evaluated at runtime and put into $myVar. So this will not work.
  • Adam Arold
    Adam Arold over 12 years
    I don't want to use reflection for this.
  • hakre
    hakre over 12 years
    There are multiple ways to achieve the same, checkout php.net/manual/en/function.constant.php - works on class constants as well.
  • Deric Lima
    Deric Lima about 7 years
    And how to solve this problem if I have a Trait with my constant and a class implementing this Trait?
  • orrd
    orrd over 6 years
    Using "print" confused me for a second because that's not really part of the solution, but yeah, using the constant() function seems to be the best way to do this.
  • Hemerson Varela
    Hemerson Varela over 5 years
    It look like is necessary to specify the class namespace if the class is on a different path.