Lendo Atributos com a API Reflection
Para acessar atributos de classes, métodos, funções, parâmetros, propriedades e constantes de classe,
a API Reflection fornece o método getAttributes() em cada um dos objetos
Reflection correspondentes. Este método retorna um array de instâncias de ReflectionAttribute
que podem ser consultadas para o nome do atributo, argumentos e para criar uma instância do atributo representado.
Essa separação da representação do atributo refletido da instância real aumenta o controle do programador
para lidar com erros relacionados a classes de atributos ausentes, erros de digitação ou argumentos ausentes. Somente após
chamar ReflectionAttribute::newInstance(), os objetos da classe de atributo são instanciados e a correspondência correta dos argumentos
é validada, não antes.
Exemplo #1 Lendo Atributos Usando a API Reflection
<?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)
}
*/
Em vez de iterar todos os atributos na instância de reflexão, apenas aqueles
de uma determinada classe de atributo podem ser
recuperados passando o nome da classe de atributo pesquisado como argumento.
Exemplo #2 Lendo Atributos Específicos Usando a API Reflection
<?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));
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 ))