PHP Conference Japan 2024

ReflectionParameter::getClass

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::getClass取得被反映參數的 ReflectionClass 物件或 null

警告

此函式自 PHP 8.0.0 起已_被棄用_。強烈建議不要依賴此函式。

說明

#[\Deprecated]
public ReflectionParameter::getClass(): ?ReflectionClass

取得被反映參數的 ReflectionClass 物件或 null

自 PHP 8.0.0 起,此函式已被棄用,不建議使用。請改用 ReflectionParameter::getType() 來獲取參數的 ReflectionType 物件,然後查詢該物件以確定參數類型。

警告

此函式目前沒有說明文件;僅提供其參數列表。

參數

此函式沒有參數。

回傳值

一個 ReflectionClass 物件,如果沒有宣告類型,或者宣告的類型不是類別或介面,則返回 null

範例

範例 #1 使用 ReflectionParameter 類別

<?php
function foo(Exception $a) { }

$functionReflection = new ReflectionFunction('foo');
$parameters = $functionReflection->getParameters();
$aParameter = $parameters[0];

echo
$aParameter->getClass()->name;
?>

更新日誌

版本 說明
8.0.0 此函式已被棄用,建議改用 ReflectionParameter::getType()

參見

新增註記

使用者貢獻的註記 5 則註記

infernaz at gmail dot com
13 年前
此方法會返回參數類型類別的 ReflectionClass 物件,如果沒有則返回 NULL。

<?php

class A {
function
b(B $c, array $d, $e) {
}
}
class
B {
}

$refl = new ReflectionClass('A');
$par = $refl->getMethod('b')->getParameters();

var_dump($par[0]->getClass()->getName()); // 輸出 B
var_dump($par[1]->getClass()); // 注意,陣列類型會輸出 NULL
var_dump($par[2]->getClass()); // 輸出 NULL

?>
tom at r dot je
12 年前
如果參數所需的類別未定義,ReflectionParameter::getClass() 將導致致命錯誤(並觸發 __autoload)。

有時,僅知道類別名稱而無需載入類別會很有用。

以下是一個簡單的函式,它只會擷取類別名稱,而無需類別存在

<?php
function getClassName(ReflectionParameter $param) {
preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
return isset(
$matches[1]) ? $matches[1] : null;
}
?>
Dylan
3 年前
適用於 php 版本 >=8
建議使用 ReflectionParamter::getType() 來取代已棄用的方法

- getClass()
例如: $name = $param->getType() && !$param->getType()->isBuiltin()
? new ReflectionClass($param->getType()->getName())
: null;

- isArray()
例如: $isArray = $param->getType() && $param->getType()->getName() === 'array';

- isCallable()
例如: $isCallable = $param->getType() && $param->getType()->getName() === 'callable';

此方法適用於 PHP 7.0 及更高版本。
tarik at bitstore dot ru
3 年前
您可以使用此函式來取代已棄用的方法

/**
* 取得參數類別
* @param \ReflectionParameter $parameter
* @return \ReflectionClass|null
*/
private function getClass(\ReflectionParameter $parameter):?\ReflectionClass
{
$type = $parameter->getType();
if (!$type || $type->isBuiltin())
return NULL;

// 此行會觸發自動載入器!
if(!class_exists($type->getName()))
return NULL;


return new \ReflectionClass($type->getName());
}
richard dot t dot rohrig at gmail dot com
4 年前
如何結合使用 getClass() 和 getConstructor() 來構建類別依賴項的範例。

private function buildDependencies(ReflectionClass $reflection)
{
$constructor = $reflection->getConstructor();

if (!$constructor) {
return [];
}

$params = $constructor->getParameters();

return array_map(function ($param) {

$className = $param->getClass();

if (!$className) {
throw new Exception();
}

$className = $param->getClass()->getName();

return $this->make($className);
}, $params);
}
To Top