
ReflectionClass::getConstants 메소드는 클래스의 상수 목록을 가져올 때, 상수명과 상수값이 같이 반환되지 않습니다.
이 메소드는 클래스의 상수 목록을 가져올 때, 상수명을 Key로 하는 Array를 반환합니다.
예를 들어, 다음 코드를 살펴보겠습니다.
#hostingforum.kr
php
class MyClass {
const MY_CONSTANT = 'Hello, World!';
}
$reflectionClass = new ReflectionClass('MyClass');
$constants = $reflectionClass->getConstants();
print_r($constants);
이 코드를 실행하면, 다음 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
[MY_CONSTANT] => Hello, World!
)
상수명과 상수값을 함께 가져올 수 있는 방법은, 클래스의 상수 목록을 가져올 때, 상수명을 Key로 하는 Array를 반환하는 메소드를 직접 구현하는 것입니다.
예를 들어, 다음 코드를 살펴보겠습니다.
#hostingforum.kr
php
class MyClass {
const MY_CONSTANT = 'Hello, World!';
}
class MyReflectionClass extends ReflectionClass {
public function getConstantsWithValues() {
$constants = $this->getConstants();
$result = array();
foreach ($constants as $name => $value) {
$result[] = array('name' => $name, 'value' => $value);
}
return $result;
}
}
$reflectionClass = new MyReflectionClass('MyClass');
$constantsWithValues = $reflectionClass->getConstantsWithValues();
print_r($constantsWithValues);
이 코드를 실행하면, 다음 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
[0] => Array
(
[name] => MY_CONSTANT
[value] => Hello, World!
)
)
이 방법을 사용하면, 클래스의 상수 목록을 가져올 때, 상수명과 상수값을 함께 가져올 수 있습니다.
2025-05-09 00:38