How do PHP 8 attributes work?

Asked

Viewed 129 times

5

In PHP 8, the attributions, which can be used in classes or methods.

Example:

namespace MyExample;

use Attribute;

#[Attribute]
class MyAttribute
{
    const VALUE = 'value';

    private $value;

    public function __construct($value = null)
    {
        $this->value = $value;
    }
}

// b.php

namespace Another;

use MyExample\MyAttribute;

#[MyAttribute]
#[\MyExample\MyAttribute]
#[MyAttribute(1234)]
#[MyAttribute(value: 1234)]
#[MyAttribute(MyAttribute::VALUE)]
#[MyAttribute(array("key" => "value"))]
#[MyAttribute(100 + 200)]
class Thing
{
}

#[MyAttribute(1234), MyAttribute(5678)]
class AnotherThing
{
}

I have some doubts about that:

  • How do I recover the values of these attributes defined in the class or method?
  • What is the purpose of the attributes? Attributes are intended to change the behavior of the method/class, or are they just extra data?
  • 7

    https://answall.com/q/484081/5878, duplicated?

  • @Woss agree that part of the question is duplicated, except for "how can I recover the defined values"?

  • 2

    In the other it is commented that it is via reflection. Perhaps you can ask the author of the reply to add an example there to make)

  • 4

    Concomitant with being duplicate, asking for examples/clarifications in comment or even putting a reward would be better than creating a new question, at least in this case

  • @Costamilam left open for community to decide. If you have an addition to the other answer, I think it’s worth closing that same.

  • I reopened the question. Details of how to implement the Attribute in the answers to the other question. The other answers only in part.

Show 1 more comment

1 answer

0


What is the purpose of the attributes? Attributes are intended to change the behavior of the method/class, or are they just extra data?

According to the documentation:

Attributes allow you to add structured and readable metadata information in code statements: classes, methods, functions, parameters, class properties and constants can be the destination of an attribute. Metadata defined by attributes can be inspected at runtime using the Reflection Apis [...]

Therefore, the attributes do not have the purpose of changing the behavior of the method or function, as in the case of Python Decorator, but only add metadata (extra information).

How do I recover the values of these attributes defined in the class or method?

As stated in the documentation, you need to use the Reflection API. The Reflection API allows you to access information from a class, function, method, parameters and etc.

Example:

#[Attribute]
class Route
{
    public function __construct(protected string $path) {}

    public function getPath()
    {
        return $this->path;
    }
}

class UsuariosController
{
    #[Route("/usuarios")]
    public function index()
    {
    }
}

You could retrieve this information like this:


$reflection_method = new ReflectionMethod(UsuariosController::class, 'index');

foreach ($reflection_method->getAttributes(Route::class) as $reflection_attribute) {

    $route = $reflection_attribute->newInstance();

    echo $route->getPath(), "\n"; // "/usuarios"
}

Note that the class that represents your custom attribute always needs to contain the declaration #[Attribute] in his statements.

Also note that the method Reflection::getAttributes returns a array of ReflectionAttribute. This is because you can declare more than one attribute in a class or method.

Behold:

class UsuariosController
{
   #[Route("/usuarios")]
   #[Route("/usuarios/listar")]
   #[RouteName("usuarios.listar")
   public function index() 
   {
      //
   }
}

In this question, there is an answer that better explains the nature of the attributes:

Browser other questions tagged

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