PHP 8.4.1 Released!

ReflectionClass::getAttributes

(PHP 8)

ReflectionClass::getAttributes获取所有属性

说明

public ReflectionClass::getAttributes(?string $name = null, int $flags = 0): array

返回类中声明的所有属性,类型是由 ReflectionAttribute 组成的 array。

参数

name

过滤结果,匹配此类名,仅包含 ReflectionAttribute 实例的属性。

flags

如果提供了 name,则用于确定如何过滤结果的 flag。

默认值为 0,这将导致返回的结果只属于类 name 的属性。

唯一可用的其他选项是使用 ReflectionAttribute::IS_INSTANCEOF,它将改为使用 instanceof 进行过滤。

返回值

ReflectionAttribute 对象组成的属性数组。

示例

示例 #1 基础用法

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

#[
Fruit]
#[
Red]
class
Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->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]
class
Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出:

Array
(
    [0] => Fruit
)

示例 #3 通过类名和继承过滤结果

<?php
interface Color {
}

#[
Attribute]
class
Fruit {
}

#[
Attribute]
class
Red implements Color {
}

#[
Fruit]
#[
Red]
class
Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->getAttributes(Color::class, ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出:

Array
(
    [0] => Red
)

添加备注

用户贡献的备注 2 notes

up
4
sandrenyl at gmail dot com
2 years ago
When using the method getAttributes() to fetch attributes based on a parent class, the proper flag constant is ReflectionAttribute::IS_INSTANCEOF (which equals 2 as mentionned by sergiolibe).

<?php
$reflectionClass
->getAttributes(SomeParentAttribute::class, ReflectionAttribute::IS_INSTANCEOF);
?>
up
3
sergiolibe at gmail dot com
3 years ago
When using getAttributes() with specific attribute class and flags, flag 0 will return just matching attributes with specified class, and 2 will return matching attributes with specified class and children of that class:
<?php
#[Attribute(\Attribute::TARGET_CLASS)]
class
SomeAttribute {}

#[
Attribute(\Attribute::TARGET_CLASS)]
class
ChildAttribute extends SomeAttribute {}

#[
SomeAttribute]
#[
SomeChildAttribute]
class
SomeClass {}

$rc = new ReflectionClass(SomeClass::class);

$r_atts = $rc->getAttributes(SomeAttribute::class, 0); // 0 is default, just given class
echo json_encode(array_map(fn(ReflectionAttribute $r_att) => $r_att->getName(), $r_atts)), PHP_EOL;

$r_atts = $rc->getAttributes(SomeAttribute::class, 2); // given class and children classes
echo json_encode(array_map(fn(ReflectionAttribute $r_att) => $r_att->getName(), $r_atts)), PHP_EOL;
?>

output:
["SomeAttribute"]
["SomeAttribute","ChildAttribute"]
To Top