Home >Backend Development >PHP Tutorial >How can you access class constants in PHP using a variable-stored name?
Accessing Class Constants with Variable-Stored Names
In object-oriented programming, class constants provide a convenient way to define immutable values within a class. However, accessing these constants using a variable that contains their names poses a challenge.
Consider the following example:
<code class="php">class A { const MY_CONST = "value"; } $myVar = "MY_CONST";</code>
In this scenario, attempting to access the value of MY_CONST using self::$myVar won't work because it refers to a static property rather than a constant.
Fortunately, there are two methods to bypass this limitation:
Constant Function:
The constant function enables access to constants defined via both define and class declarations. It takes the form constant('::'), where :: represents the namespace and constName specifies the constant's name.
<code class="php">$c = 'MY_CONST'; echo constant('::' . $c); // Output: value</code>
Reflection Class:
Using the Reflection API, one can access class constants through a reflection class instance.
<code class="php">$ref = new ReflectionClass('A'); $constName = 'MY_CONST'; echo $ref->getConstant($constName); // Output: value</code>
The above is the detailed content of How can you access class constants in PHP using a variable-stored name?. For more information, please follow other related articles on the PHP Chinese website!