Nombre de constante dinámica en PHP


Estoy tratando de crear un nombre constante dinámicamente y luego obtener el valor.

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;

Pero encuentro que constant constant value todavía contiene el NOMBRE de la constante, y no el VALOR.

Probé el segundo nivel de indirección también $$constant_name Pero eso lo haría una variable no una constante.

¿Puede alguien arrojar algo de luz sobre esto?

Author: Elnur Abdurrakhimov, 2010-10-22

3 answers

 122
Author: Mads Lee Jensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-22 08:46:05

Y para demostrar que esto también funciona con constantes de clase:

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

$command = "HELLO";
echo constant("Joshua::SAY_$command");
 49
Author: DonVaughn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-27 20:10:09

Para usar nombres de constantes dinámicas en su clase puede usar la característica de reflexión (desde php5):

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

Por ejemplo: si desea filtrar solo constantes específicas (SORT_*) en la clase

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());

Resultado:

array (size=2)
  0 => int 1
  1 => int 2
 5
Author: Dado,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-18 11:38:16