
ReflectionFunctionAbstract::getReturnType 메소드는 함수의 반환 타입을 가져올 수 있습니다. 그러나 null을 반환할 수 있는 경우도 있습니다.
예를 들어, 다음 코드가 있다고 가정해 보겠습니다.
#hostingforum.kr
php
function testFunction(): string {
return 'Hello, World!';
}
function testFunction2(): ?string {
return null;
}
이 경우, `ReflectionFunctionAbstract::getReturnType`를 사용하여 반환 타입을 가져올 수 있습니다.
#hostingforum.kr
php
$reflection = new ReflectionFunction('testFunction');
echo $reflection->getReturnType()->getName(); // string
$reflection2 = new ReflectionFunction('testFunction2');
echo $reflection2->getReturnType()->getName(); // string|null
null을 반환할 수 있는 경우는 다음과 같습니다.
- 함수가 null을 반환하는 경우
- 함수가 nullable 타입을 반환하는 경우
- 함수가 void를 반환하는 경우 (void는 null과 동일)
이러한 경우를 예외 처리 하기 위한 방법은 다음과 같습니다.
#hostingforum.kr
php
$reflection = new ReflectionFunction('testFunction');
if ($reflection->getReturnType()->allowsNull()) {
echo "함수는 null을 반환할 수 있습니다.";
} else {
echo "함수는 null을 반환하지 않습니다.";
}
$reflection2 = new ReflectionFunction('testFunction2');
if ($reflection2->getReturnType()->allowsNull()) {
echo "함수는 null을 반환할 수 있습니다.";
} else {
echo "함수는 null을 반환하지 않습니다.";
}
또한, nullable 타입을 확인하기 위한 방법은 다음과 같습니다.
#hostingforum.kr
php
$reflection = new ReflectionFunction('testFunction2');
if ($reflection->getReturnType()->isNullable()) {
echo "함수는 nullable 타입을 반환합니다.";
} else {
echo "함수는 nullable 타입을 반환하지 않습니다.";
}
2025-07-27 13:05