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