IT박스

PHP의 동적 상수 이름

itboxs 2020. 10. 31. 09:30

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 값에는 여전히 VALUE가 아닌 상수의 NAME이 포함되어 있습니다.

두 번째 수준의 간접도 시도했지만 $$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

참고 URL : https://stackoverflow.com/questions/3995197/dynamic-constant-name-in-php