programing

PHP의 동적 상수 이름

goodcopy 2022. 11. 6. 13:32
반응형

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

반응형