(PHP 8)
ReflectionParameter::getAttributes — 取得屬性
以 ReflectionAttribute 陣列形式返回在此參數上宣告的所有屬性。
name
篩選結果,僅包含與此類別名稱相符的屬性的 ReflectionAttribute 實例。
flags
用於決定如何篩選結果的旗標,如果提供了 name
參數的話。
預設值為 0
,這將只會返回屬於 name
類別的屬性結果。
另一個可用的選項是使用 ReflectionAttribute::IS_INSTANCEOF
,它將改用 instanceof
進行篩選。
屬性陣列,以 ReflectionAttribute 物件呈現。
範例 #1 基本用法
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }
$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>
上述範例將輸出
Array ( [0] => Fruit [1] => Red )
範例 #2 透過類別名稱篩選結果
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }
$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>
上述範例將輸出
Array ( [0] => Fruit )
範例 #3 按類別名稱篩選結果,含繼承
<?php
interface Color {
}
#[Attribute]
class Fruit {
}
function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }
$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>
上述範例將輸出
Array ( [0] => Red )