PHP Conference Japan 2024

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 開始,此方法可能會傳回 ReflectionNamedType 實例或 ReflectionUnionType 實例。後者是前者的集合。若要分析型別,通常方便將其正規化為 ReflectionNamedType 物件的陣列。下列函式將傳回包含 0 或多個 ReflectionNamedType 實例的陣列。

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

if (!
$reflectionType) return [];

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

另請參閱

新增註解

使用者貢獻的註解 1 則註解

Will Beaumont
4 年前
從 7.1 開始,如果找到參數型別,則此方法會傳回 ReflectionNamedType 的實例 (https://php.dev.org.tw/manual/en/class.reflectionnamedtype.php),它是 ReflectionType 的子類別。
To Top