라이브러리
[PHP] ReflectionClass::getConstants - 상수를 가져옵니다.
ReflectionClass::getConstants
PHP의 ReflectionClass::getConstants 메소드는 클래스의 상수(constant)를 반환합니다. 이 메소드는 ReflectionClass 인스턴스에 호출할 수 있으며, 클래스의 상수를 가져올 수 있습니다.
사용법
ReflectionClass::getConstants 메소드는 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
php
$reflectionClass = new ReflectionClass('클래스 이름');
$constants = $reflectionClass->getConstants();
예제
다음 예제는 ReflectionClass::getConstants 메소드를 사용하여 클래스의 상수를 가져오는 방법을 보여줍니다.
#hostingforum.kr
php
class ConstantsExample {
const PI = 3.14;
const E = 2.71;
}
$reflectionClass = new ReflectionClass('ConstantsExample');
$constants = $reflectionClass->getConstants();
print_r($constants);
이 예제를 실행하면 다음 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
[PI] => 3.14
[E] => 2.71
)
예제 2: 상수 이름과 값 가져오기
다음 예제는 ReflectionClass::getConstants 메소드를 사용하여 클래스의 상수 이름과 값을 가져오는 방법을 보여줍니다.
#hostingforum.kr
php
class ConstantsExample {
const PI = 3.14;
const E = 2.71;
}
$reflectionClass = new ReflectionClass('ConstantsExample');
$constants = $reflectionClass->getConstants();
foreach ($constants as $name => $value) {
echo "$name: $value
";
}
이 예제를 실행하면 다음 결과가 출력됩니다.
#hostingforum.kr
PI: 3.14
E: 2.71
예제 3: 상수 이름만 가져오기
다음 예제는 ReflectionClass::getConstants 메소드를 사용하여 클래스의 상수 이름만 가져오는 방법을 보여줍니다.
#hostingforum.kr
php
class ConstantsExample {
const PI = 3.14;
const E = 2.71;
}
$reflectionClass = new ReflectionClass('ConstantsExample');
$constants = $reflectionClass->getConstants();
foreach ($constants as $name => $value) {
echo "$name
";
}
이 예제를 실행하면 다음 결과가 출력됩니다.
#hostingforum.kr
PI
E
예제 4: 상수 이름과 값이 없는 클래스
다음 예제는 ReflectionClass::getConstants 메소드를 사용하여 상수 이름과 값이 없는 클래스의 상수를 가져오는 방법을 보여줍니다.
#hostingforum.kr
php
class NoConstants {
}
$reflectionClass = new ReflectionClass('NoConstants');
$constants = $reflectionClass->getConstants();
print_r($constants);
이 예제를 실행하면 다음 결과가 출력됩니다.
#hostingforum.kr
php
Array
(
)
결론
ReflectionClass::getConstants 메소드는 클래스의 상수를 가져올 수 있는 유용한 메소드입니다. 이 메소드를 사용하여 클래스의 상수 이름과 값을 가져올 수 있습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.