Retrieving the attributes' parameters of a PHP class with reflection

Published on 2023-01-26 • Modified on 2023-01-26

This snippet shows how to retrieving the attributes' parameters of a PHP class with reflection. As you can see, it's straightforward. We can get the arguments as an associative array.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet241Trait
{
    public function snippet241(): void
    {
        $refl = new \ReflectionClass($this::class);
        $attributes = $refl->getAttributes();
        $routeAttribute = $attributes[0]; // #[Route()] attribute in SnippetController

        echo "Attribute's name: ".$routeAttribute->getName().PHP_EOL;
        echo "Attribute's arguments: ";
        print_r($routeAttribute->getArguments());

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!