개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.05.09 00:36

ReflectionClass::getConstants 관련 질문

목록
  • 웹앱구루 1일 전 2025.05.09 00:36
  • 2
    1
제가 ReflectionClass::getConstants 메소드를 사용하여 클래스의 상수 목록을 얻으려 하지만, 이 메소드는 클래스의 상수를 모두 가져오지만, 상수명과 상수값이 같이 가져오지 않는 것 같습니다.

getConstants 메소드가 반환하는 값은 무엇이며, 상수명과 상수값을 함께 가져올 수 있는 방법은 없나요?

    댓글목록

    profile_image
    나우호스팅  1일 전



    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

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 18,243건 / 27 페이지

검색

게시물 검색