개발자 Q&A

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

2025.07.15 00:58

ReflectionParameter::__toString 이해에 도움이 필요합니다.

목록
  • JetpackCompose마… 6일 전 2025.07.15 00:58
  • 17
    1
제가 ReflectionParameter 클래스의 __toString 메서드를 사용해 보았는데, 어떤 경우에는 파라미터 이름과 타입이 잘 출력되지만 어떤 경우에는 이름만 출력됩니다.
예를 들어 다음과 같은 경우

php

$reflectionMethod = new ReflectionMethod('MyClass', 'myMethod');

$reflectionParameter = $reflectionMethod->getParameters()[0];

echo $reflectionParameter->getName() . "n"; // myParam

echo $reflectionParameter->getType() . "n"; // string



이 경우에는 이름과 타입이 모두 잘 출력됩니다.
하지만 다음과 같은 경우

php

$reflectionClass = new ReflectionClass('MyClass');

$reflectionProperty = $reflectionClass->getProperty('myProperty');

echo $reflectionProperty->getName() . "n"; // myProperty

echo $reflectionProperty->getType() . "n"; // 



이 경우에는 이름만 출력되고 타입은 빈 문자열로 출력됩니다.
이러한 이유는 무엇이며, 어떻게 하면 ReflectionParameter::__toString 메서드가 타입을 올바르게 출력할 수 있을까요?

    댓글목록

    profile_image
    나우호스팅  6일 전



    ReflectionParameter 클래스의 __toString 메서드는 파라미터 이름과 타입을 출력합니다. 하지만, 타입이 올바르게 출력되지 않는 경우가 있습니다.

    이러한 이유는 ReflectionParameter 클래스의 getType 메서드가 null을 반환할 때입니다. getType 메서드는 파라미터의 타입을 반환하지만, null을 반환할 수 있습니다.

    예를 들어, 다음과 같은 경우에는 getType 메서드가 null을 반환합니다.

    #hostingforum.kr
    php
    
    $reflectionClass = new ReflectionClass('MyClass');
    
    $reflectionProperty = $reflectionClass->getProperty('myProperty');
    
    echo $reflectionProperty->getName() . "n"; // myProperty
    
    echo $reflectionProperty->getType() . "n"; // (null)
    
    


    이러한 경우에는 ReflectionParameter 클래스의 __toString 메서드가 null을 반환하기 때문에 타입이 빈 문자열로 출력됩니다.

    타입을 올바르게 출력하기 위해서는 getType 메서드가 null을 반환하지 않도록 해야 합니다.

    예를 들어, 다음과 같이 getType 메서드가 null을 반환하지 않도록 할 수 있습니다.

    #hostingforum.kr
    php
    
    $reflectionClass = new ReflectionClass('MyClass');
    
    $reflectionProperty = $reflectionClass->getProperty('myProperty');
    
    if ($reflectionProperty->getType() !== null) {
    
        echo $reflectionProperty->getName() . "n"; // myProperty
    
        echo $reflectionProperty->getType() . "n"; // string
    
    } else {
    
        echo $reflectionProperty->getName() . "n"; // myProperty
    
        echo '타입이 없습니다.' . "n";
    
    }
    
    


    또는, ReflectionParameter 클래스의 __toString 메서드를 오버라이딩하여 null을 반환하지 않도록 할 수 있습니다.

    #hostingforum.kr
    php
    
    class MyReflectionParameter extends ReflectionParameter {
    
        public function __toString() {
    
            if ($this->getType() !== null) {
    
                return $this->getName() . ' (' . $this->getType() . ')';
    
            } else {
    
                return $this->getName();
    
            }
    
        }
    
    }
    
    


    이러한 방법으로 ReflectionParameter 클래스의 __toString 메서드가 타입을 올바르게 출력할 수 있습니다.

    2025-07-15 00:59

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

검색

게시물 검색