Dynamic constant name in PHP

后端 未结 3 845
不知归路
不知归路 2020-11-27 15:54

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 ...
$const         


        
相关标签:
3条回答
  • 2020-11-27 16:17

    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
    
    0 讨论(0)
  • 2020-11-27 16:27

    http://dk.php.net/manual/en/function.constant.php

    echo constant($constant_name);
    
    0 讨论(0)
  • 2020-11-27 16:37

    And to demonstrate that this works with class constants too:

    class Joshua {
        const SAY_HELLO = "Hello, World";
    }
    
    $command = "HELLO";
    echo constant("Joshua::SAY_$command");
    
    0 讨论(0)
提交回复
热议问题