betterCode() PHP 2025

使用反射 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 note

up
7
Hirusha Sharma
4 years ago
Fetch properties from functions:

----------------------------------------
Function definition with attributes:
----------------------------------------
#[ReadOnly]
#[Property(type: 'function', name: 'Hello')]
function Hello()
{
return "Hello";
}

-----------------------------------------
Gather attributes from the function
-----------------------------------------
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));

-----------------------------
OUTPUT
-----------------------------
Array
(
[ReadOnly] => Array
(
)

[Property] => Array
(
[type] => function
[name] => Hello
)

)
To Top