Dynamic constant name in PHP

PhpConstantsIndirection

Php Problem Overview


I am trying to create a constant name dynamically and then get at the value.

define( CONSTANT_1 , "Some value" ) ;

// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;

// try to assign the constant value to a variable...
$constant_value = $constant_name;

But I find that $constant value still contains the NAME of the constant, and not the VALUE.

I tried the second level of indirection as well $$constant_name But that would make it a variable not a constant.

Can somebody throw some light on this?

Php Solutions


Solution 1 - Php

Solution 2 - Php

And to demonstrate that this works with class constants too:

class Joshua {
    const SAY_HELLO = "Hello, World";
}

$command = "HELLO";
echo constant("Joshua::SAY_$command");

Solution 3 - Php

To use dynamic constant names in your class you can use reflection feature (since php5):

$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);

For example: if you want to filter only specific (SORT_*) constants in the class

class MyClass 
{
    const SORT_RELEVANCE = 1;
    const SORT_STARTDATE = 2;

    const DISTANCE_DEFAULT = 20;

    public static function getAvailableSortDirections()
    {
        $thisClass = new ReflectionClass(__CLASS__);
        $classConstants = array_keys($thisClass->getConstants());

        $sortDirections = [];
        foreach ($classConstants as $constName) {
            if (0 === strpos($constName, 'SORT_')) {
                $sortDirections[] =  $thisClass->getConstant($constName);
            }
        }

        return $sortDirections;
    }
}

var_dump(MyClass::getAvailableSortDirections());

result:

array (size=2)
  0 => int 1
  1 => int 2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvikmalhotraView Question on Stackoverflow
Solution 1 - PhpMads Lee JensenView Answer on Stackoverflow
Solution 2 - PhpuɥƃnɐʌuopView Answer on Stackoverflow
Solution 3 - PhpDadoView Answer on Stackoverflow