略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 使用反射 API 读取注解

2024-04-29

使用反射 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));
add a noteadd a note

User Contributed Notes 1 note

up
3
Hirusha Sharma
1 year 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
        )

)

官方地址:https://www.php.net/manual/en/language.attributes.reflection.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3