(PHP 8)
ReflectionFunctionAbstract::getAttributes — 获取属性
返回声明在此函数或方法上的所有属性,作为 ReflectionAttribute 对象的数组。
name筛选结果,仅包含与该类名匹配的属性的 ReflectionAttribute 实例。
flags如果提供了 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
)