Reflection ReflectionParameter::getType

(PHP 7, PHP 8)

ReflectionParameter::getType — 매개변수의 유형을 가져옵니다.


설명

public ReflectionParameter::getType(): ?ReflectionType

매개변수의 연관된 유형을 가져옵니다.


매개변수

이 함수에는 매개변수가 없습니다.


반환 값

매개변수 유형이 지정되면 ReflectionType 개체를 반환하고 그렇지 않으면 null을 반환합니다.


Examples

예제 #1 ReflectionParameter::getType() PHP 7.1.0부터 사용

PHP 7.1.0부터 ReflectionType::__toString()은 더 이상 사용되지 않으며 ReflectionParameter::getType()ReflectionNamedType의 인스턴스를 반환할 수 있습니다. 이 경우 매개변수 유형의 이름을 가져오기 위해 ReflectionNamedType()을 사용할 수 있습니다.

                  
<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

assert($reflectionType1 instanceof ReflectionNamedType);
echo $reflectionType1->getName(), PHP_EOL;
var_dump($reflectionType2);
?>
                  
                

위의 예는 다음을 출력합니다.

int
NULL
                

예제 #2 ReflectionParameter::getType() PHP 7.1.0 이전 사용

                  
<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

echo $reflectionType1, PHP_EOL;
var_dump($reflectionType2);
?>
                  
                

PHP 7.0에서 위 예제의 출력:

int
NULL
                

예제 #3 ReflectionParameter::getType() PHP 8.0.0 이상에서의 사용법

PHP 8.0.0부터 이 메서드는 ReflectionNamedType 인스턴스 또는 ReflectionUnionType 인스턴스를 반환할 수 있습니다. 후자는 전자의 모음입니다. 유형을 분석하려면 ReflectionNamedType 객체의 배열로 정규화하는 것이 편리한 경우가 많습니다. 다음 함수는 0개 이상의 ReflectionNamedType 인스턴스의 배열을 반환합니다.

                  
<?php
function getAllTypes(ReflectionParameter $reflectionParameter): array
{
    $reflectionType = $reflectionParameter->getType();

    if (!$reflectionType) return [];

    return $reflectionType instanceof ReflectionUnionType
        ? $reflectionType->getTypes()
        : [$reflectionType];
}
?>
                  
                

기타