PHP Conference Japan 2024

ReflectionParameter 類別

(PHP 5, PHP 7, PHP 8)

簡介

ReflectionParameter 類別會擷取關於函式或方法參數的資訊。

若要內省函式參數,首先建立 ReflectionFunctionReflectionMethod 類別的實例,然後使用它們的 ReflectionFunctionAbstract::getParameters() 方法來擷取參數陣列。

類別概要

class ReflectionParameter implements Reflector {
/* 屬性 */
public string $name;
/* 方法 */
public __construct(string|array|object $function, int|string $param)
public allowsNull(): bool
private __clone(): void
public static export(string $function, string $parameter, bool $return = ?): string
public getAttributes(?string $name = null, int $flags = 0): array
public getName(): string
public getPosition(): int
public hasType(): bool
public isOptional(): bool
public isPromoted(): bool
public isVariadic(): bool
public __toString(): string
}

屬性

name

參數的名稱。唯讀,嘗試寫入時會拋出 ReflectionException

變更記錄

版本 描述
8.0.0 ReflectionParameter::export() 已移除。

目錄

新增筆記

使用者貢獻筆記 4 筆筆記

fgm at riff dot org
16 年前
關於 ReflectionParameter 建構函式的簽名 (signature) 的筆記實際上是不完整的,至少在 5.2.5 中是這樣:可以使用整數作為第二個參數,而建構函式會使用它來傳回第 n 個參數。

這允許您即使在記錄來自擴充套件的程式碼時,也能取得正確的 ReflectionParameter 物件,這些擴充套件(奇怪的是)定義了數個名稱相同的參數。基於字串的建構函式總是傳回第一個具有匹配名稱的參數,而基於整數的建構函式則正確地傳回第 n 個參數。

簡而言之,這樣有效
<?php
// 假設擴充套件定義了如下內容:
// Some_Class::someMethod($a, $x, $y, $x, $y)
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 4);
// 傳回最後一個參數,而
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 'y');
// 總是傳回位於位置 2 的第一個 $y
?>
killgecNOFSPAM at gmail dot com
17 年前
ReflectionParameter 的建構函式簽名正確為

public function __construct(array/string $function, string $name);

其中 $function 可以是全域函式的名稱,或類別/方法名稱配對。
massimo at mmware dot it
17 年前
我發現從 ReflectionFunction 使用類別 ReflectionParameter 與內部函式 (例如 print_r, str_replace, ... ) 時存在這些限制

1. 參數名稱與手冊不符:(嘗試使用 arg "call_user_func" 的範例 19.35)
2. 某些函式(例如 PCRE 函式、preg_match 等)具有空的參數名稱
3. 在參數上呼叫 getDefaultValue 將導致例外「無法確定內部函式的預設值」
rasmus at mindplay dot dk
1 年前
現在有太多的參數模式,我需要確切知道 `ReflectionParameter` 將會傳回什麼,所以我寫了一個小測試腳本 - 您可以在這裡找到該腳本和表格中的結果

https://gist.github.com/mindplay-dk/082458088988e32256a827f9b7491e17
To Top