라이브러리

[PHP] ReflectionClass::getConstant - 정의된 상수를 가져옵니다.




ReflectionClass::getConstant


PHP ReflectionClass::getConstant 메소드는 클래스의 상수 이름을 가져오는 데 사용됩니다. 이 메소드는 ReflectionClass 인스턴스에 대해 호출됩니다.

# 예제


#hostingforum.kr
php

class MyClass {

    const MY_CONSTANT = 'Hello, World!';

}



$reflectionClass = new ReflectionClass('MyClass');

$constant = $reflectionClass->getConstant('MY_CONSTANT');



echo $constant; // 출력: Hello, World!



# 사용 방법


1. ReflectionClass 인스턴스를 생성합니다.
2. getConstant 메소드를 호출하여 클래스의 상수 이름을 가져옵니다.
3. 가져온 상수 이름을 사용하여 상수를 가져옵니다.

# 예제 2 - 상수 이름이 여러 개 있는 클래스


#hostingforum.kr
php

class MyClass {

    const MY_CONSTANT1 = 'Hello, World!';

    const MY_CONSTANT2 = 'Goodbye, World!';

}



$reflectionClass = new ReflectionClass('MyClass');

$constant1 = $reflectionClass->getConstant('MY_CONSTANT1');

$constant2 = $reflectionClass->getConstant('MY_CONSTANT2');



echo $constant1; // 출력: Hello, World!

echo $constant2; // 출력: Goodbye, World!



# 예제 3 - 상수가 없는 클래스


#hostingforum.kr
php

class MyClass {}



$reflectionClass = new ReflectionClass('MyClass');

try {

    $constant = $reflectionClass->getConstant('MY_CONSTANT');

} catch (ReflectionException $e) {

    echo '클래스에 상수가 없습니다.';

}



# 예제 4 - 상수 이름이 잘못된 클래스


#hostingforum.kr
php

class MyClass {}



$reflectionClass = new ReflectionClass('MyClass');

try {

    $constant = $reflectionClass->getConstant('MY_CONSTANT');

} catch (ReflectionException $e) {

    echo '클래스에 상수가 없습니다.';

}



# 예제 5 - 상수 이름이 여러 개 있는 클래스 (배열로 가져오기)


#hostingforum.kr
php

class MyClass {

    const MY_CONSTANT1 = 'Hello, World!';

    const MY_CONSTANT2 = 'Goodbye, World!';

}



$reflectionClass = new ReflectionClass('MyClass');

$constants = $reflectionClass->getConstants();



foreach ($constants as $constantName => $constantValue) {

    echo "$constantName: $constantValue
";

}



이 예제는 getConstants 메소드를 사용하여 클래스의 모든 상수를 가져와 배열로 출력합니다.

# 예제 6 - 상수 이름이 여러 개 있는 클래스 (배열로 가져오기 - 필터링)


#hostingforum.kr
php

class MyClass {

    const MY_CONSTANT1 = 'Hello, World!';

    const MY_CONSTANT2 = 'Goodbye, World!';

}



$reflectionClass = new ReflectionClass('MyClass');

$constants = $reflectionClass->getConstants();



$filteredConstants = array_filter($constants, function($constantName) {

    return strpos($constantName, 'MY_CONSTANT') === 0;

});



foreach ($filteredConstants as $constantName => $constantValue) {

    echo "$constantName: $constantValue
";

}



이 예제는 getConstants 메소드를 사용하여 클래스의 모든 상수를 가져와 배열로 출력한 후, 필터링하여 MY_CONSTANT로 시작하는 상수만 출력합니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 292 페이지

검색

게시물 검색