使用反射 API 讀取注解

反射 API 提供了 getAttributes() 方法, 類、方法、函數(shù)、參數(shù)、屬性、類常量的反射對象可通過它獲取相應(yīng)的注解。 該方法返回了 ReflectionAttribute 實(shí)例的數(shù)組, 可用于查詢注解名稱、參數(shù)、也可以實(shí)例化一個(gè)注解。

實(shí)例和反射注解的分離使得程序員增加了在丟失反射類、類型錯(cuò)誤、丟失參數(shù)等情況下的處理能力,也能處理錯(cuò)誤。 只有調(diào)用 ReflectionAttribute::newInstance() 后,注解類的對象才會以驗(yàn)證過匹配的參數(shù)來實(shí)例化。

示例 #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)
}
*/

通過傳入?yún)?shù):待搜索的注解類名,可返回指定的注解類, 而不需要再到反射類中迭代循環(huán)獲取所有注解。

示例 #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));