簡體   English   中英

PHP 中的動態常量名

[英]Dynamic constant name in PHP

我正在嘗試動態創建一個常量名稱,然后獲取該值。

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;

但我發現 $constant 值仍然包含常量的 NAME,而不是 VALUE。

我也嘗試了第二級間接$$constant_name但這會使它成為一個變量而不是一個常量。

有人可以對此有所了解嗎?

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

echo constant($constant_name);

並證明這也適用於類常量:

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

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

要在您的類中使用動態常量名稱,您可以使用反射功能(自 php5 起):

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

例如:如果您只想過濾類中的特定 (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());

結果:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM