ReflectionParameter::getType

(PHP 7, PHP 8)

ReflectionParameter::getType引数の型を取得する

説明

public ReflectionParameter::getType(): ?ReflectionType

引数の型を取得します。

パラメータ

この関数にはパラメータはありません。

戻り値

引数の型が指定されていれば ReflectionType オブジェクトを返します。 そうでなければ null を返します。

例1 PHP 7.1.0 以降での ReflectionParameter::getType() の使い方

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 PHP 7.1.0 より前の ReflectionParameter::getType() の使い方

<?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 PHP 8.0.0 以降の ReflectionParameter::getType() の使い方

PHP 8.0.0 以降では、このメソッドは ReflectionNamedTypeReflectionUnionType のインスタンスを返す可能性があります。 後者は前者の集合です。後者の型を解析するには、 ReflectionNamedType の配列に正規化する方が便利です。 以下の例に示す関数は、0 または ReflectionNamedType のインスタンスの配列を返します。

<?php
function getAllTypes(ReflectionParameter $reflectionParameter): array
{
$reflectionType = $reflectionParameter->getType();
if (!
$reflectionType) return [];
return
$reflectionType instanceof ReflectionUnionType
? $reflectionType->getTypes()
: [
$reflectionType];
}
?>

参考

add a note

User Contributed Notes 1 note

up
0
Will Beaumont
3 years ago
As of 7.1, if a parameter type is found then this method returns an instance of ReflectionNamedType (https://www.php.net/manual/en/class.reflectionnamedtype.php), a subclass of ReflectionType.
To Top