2024 年日本 PHP 研討會

使用反射 API 讀取屬性

為了從類別、方法、函式、參數、屬性和類別常數存取屬性,反射 API 在每個對應的反射物件上提供了 getAttributes() 方法。此方法會傳回一個 ReflectionAttribute 實例的陣列,可以查詢屬性名稱、引數,並實例化所表示屬性的一個實例。

將反射屬性表示與實際實例分開,增加了程式設計師控制遺漏屬性類別、輸入錯誤或遺漏引數等錯誤的能力。只有在呼叫 ReflectionAttribute::newInstance() 之後,才會實例化屬性類別的物件,並驗證引數的正確匹配,而不是更早之前。

範例 #1 使用反射 API 讀取屬性

<?php

#[Attribute]
class
MyAttribute
{
public
$value;

public function
__construct($value)
{
$this->value = $value;
}
}

#[
MyAttribute(value: 1234)]
class
Thing
{
}

function
dumpAttributeData($reflection) {
$attributes = $reflection->getAttributes();

foreach (
$attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}

dumpAttributeData(new ReflectionClass(Thing::class));
/*
string(11) "MyAttribute"
array(1) {
["value"]=>
int(1234)
}
object(MyAttribute)#3 (1) {
["value"]=>
int(1234)
}
*/

除了迭代反射實例上的所有屬性之外,還可以透過傳入搜尋的屬性類別名稱作為參數,僅擷取特定屬性類別的屬性。

範例 #2 使用反射 API 讀取特定屬性

<?php

function dumpMyAttributeData($reflection) {
$attributes = $reflection->getAttributes(MyAttribute::class);

foreach (
$attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}

dumpMyAttributeData(new ReflectionClass(Thing::class));
新增筆記

使用者貢獻的筆記 1 則筆記

Hirusha Sharma
3 年前
從函式擷取屬性

----------------------------------------
具有屬性的函式定義
----------------------------------------
#[ReadOnly]
#[Property(type: 'function', name: 'Hello')]
function Hello()
{
return "Hello";
}

-----------------------------------------
從函式收集屬性
-----------------------------------------
function getAttributes(Reflector $reflection)
{
$attributes = $reflection->getAttributes();
$result = [];
foreach ($attributes as $attribute)
{
$result[$attribute->getName()] = $attribute->getArguments();
}
return $result;
}

$reflection = new ReflectionFunction("Hello");
print_r(getAttributes($reflection));

-----------------------------
輸出
-----------------------------
陣列
(
[ReadOnly] => 陣列
(
)

[Property] => 陣列
(
[type] => function
[name] => Hello
)

)
To Top