
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