반응형
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
반응형
'programing' 카테고리의 다른 글
| PHP mysql 삽입 날짜 형식 (0) | 2022.11.07 |
|---|---|
| 저는 json 데이터를 가진 authorsjson이라는 JSON 컬럼을 가지고 있습니다.이름이 지정된 문자열로 시작하는 모든 사용자를 찾습니다. (0) | 2022.11.07 |
| #1030 - 스토리지 엔진 Aria에서 오류 176 "잘못된 체크섬으로 페이지 읽기"가 표시됨 (0) | 2022.11.06 |
| C에서 uint32_t를 바이너리로 변환하는 중 (0) | 2022.11.06 |
| 스프링 Jpa Repository의 %Like% 쿼리 (0) | 2022.11.06 |