Reading Attributes with Reflection API in PHP 8


In PHP 8, we use classes, properties, and class constants, methods, functions, parameters to access the attributes.

In PHP 8, Reflection API delivers the getAttribute() method on every matching Reflection object.

The getAttribute() method returns an array of ReflectionAttribute illustrations that can be asked for attribute name, arguments and to instantiate an instance of the signified attribute.

Example − Reading Attributes with the Reflection API in PHP 8

<?php
   #[Reading]
   #[Property(type: 'function', name: 'Student')]
   function Student()
   {
      return "Student";
   }
   function getAttributes(Reflector $reflection)
   {
      $attributes = $reflection->getAttributes();
      $finalresult = [];
      foreach ($attributes as $attribute)
      {
         $finalresult[$attribute->getName() ] = $attribute->getArguments();
      }
      return $finalresult;
   }
   $reflection = new ReflectionFunction("Student");
   print_r(getAttributes($reflection));
?>

Output

Array
(
   [Reading] => Array
   (
   )

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

Updated on: 01-Apr-2021

544 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements