How to access PHP 8 attributes (or Annotations)?

Asked

Viewed 32 times

0

I’m experimenting with the attributes (or Annotations) PHP 8. I created some sample classes and added the class, property and method attributes.

<?php

#[Attribute]
class ClassAttribute {}

#[Attribute]
class PropertyAttribute {}

#[Attribute]
class MethodAttribute {}

#[ClassAttribute]
class Sample {
    #[PropertyAttribute]
    protected $myAttribute;

    #[MethodAttribute]
    public function myFunction() {}
}

How to access these attributes with Reflection? In the documentation of classes of Reflection there are no attribute methods for examples of attributes.

1 answer

0


You can access class, property and method attributes using the method getAttributes() (not yet documented) respectively of the classes ReflectionClass, ReflectionProperty and ReflectionMethod:

$classReflection = new ReflectionClass(Sample::class);
$classAttributes = $classReflection->getAttributes();

$methodReflection = new ReflectionMethod(Sample::class, 'myFunction');
$methodAttributes = $methodReflection->getAttributes();

$propertyReflection = new ReflectionProperty(Sample::class, 'myAttribute');
$propertyAttributes = $propertyReflection->getAttributes();

For the class it is possible to use also the ReflectionObject.

Thus $classAttributes, $methodAttributes and $propertyAttributes sane arrays of instances of ReflectionAttribute (not yet documented either), from which it is possible to call the methods of the examples in the documentation:

$classAttributes[0]->getName();
$classAttributes[0]->getArguments();
$classAttributes[0]->newInstance();

When executing var_dump in these methods the following is displayed:

string(14) "ClassAttribute"
array(0) {
}
object(ClassAttribute)#7 (0) {
}

This way works when the name of the properties or methods is known. When the name is unknown it is necessary to iterate the instance of ReflectionObject or ReflectionClass with getProperties or getMethods. These functions return arrays containing instances of ReflectionProperty and ReflectionMethod, of which the attributes can be obtained according to the above example.

$classReflection = new ReflectionClass(Sample::class);
$classMethods = $classReflection->getMethods();
foreach ($classMethods as $methodReflection) {
  $methodReflection->getAttributes();
}
$classMethods = $classReflection->getProperties();
foreach ($classProperties as $propertyReflection) {
  $propertyReflection->getAttributes();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.