PHP中的动态常量名称

vik*_*tra 72 php constants indirection

我试图动态创建一个常量名称,然后获取该值.

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;
Run Code Online (Sandbox Code Playgroud)

但是我发现$ constant值仍然包含常量的NAME,而不是VALUE.

我也尝试了第二级间接$$constant_name但是这会使它变量而不是常量.

有人可以对此有所了解吗?

Don*_*ghn 60

并证明这也适用于类常量:

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

$command = "HELLO";
echo constant("Joshua::SAY_$command");
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,如果常量位于不在当前命名空间中的类中,则可能需要指定完全限定(命名空间)类名 - 无论是否在文件中为类添加了"use". (7认同)
  • @lopsided` :: class`常量可用于检索完全限定的命名空间,例如:`constant(YourClass :: class.':: CONSTANT_'.$ yourVariable);` (5认同)

Dad*_*ado 7

要在类中使用动态常量名称,可以使用反射功能(因为php5):

$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);
Run Code Online (Sandbox Code Playgroud)

例如:如果要仅过滤类中的特定(SORT_*)常量

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());
Run Code Online (Sandbox Code Playgroud)

结果:

array (size=2)
  0 => int 1
  1 => int 2
Run Code Online (Sandbox Code Playgroud)