Using PHP attributes easily

Nacho Colomina Torregrosa - Jan 30 '23 - - Dev Community

PHP attributes are a new feature included in the last php 8 version which allow us to easily add metadata to our classes, methods and properties.

Creating an attribute is easy, we only have to create a class, define its properties and mark it as attribute. Let's see an example


    #[\Attribute]
    class IsBackground
    {
        public function __construct(
            public readonly ?int $delay = null
        ){ }
     }

Enter fullscreen mode Exit fullscreen mode

In the above code, we've created an attribute called IsBackground which holds one parameter: delay.

Now let's see how we could use it. Imagine we have a class called Operation which we want to decorate as "IsBackground".


    #[IsBackground]
    class Operation {

        // properties and methods
    }

Enter fullscreen mode Exit fullscreen mode

As we can see, it's already marked simply using #[IsBackground] at the top of the class.

Now, let's see how to read attribute data:

     $reflectionClass = new \ReflectionClass(new Operation());
     $attributes = $reflectionClass->getAttributes(IsBackground::class);
     $attr = reset($attributes);
     $attrObject = $attr->newInstance();

     echo $attrObject->delay;
Enter fullscreen mode Exit fullscreen mode

When we decorated Operation with IsBackground attribute we defined no delay. In order to set a delay, we would change Operation class like this:

#[IsBackground(delay: 600)]
class Operation {

    // properties and methods
}
Enter fullscreen mode Exit fullscreen mode

If you want to learn how i used PHP attributes to define API operations, you can read this post or read my book: Building an operation-oriented api using PHP and the Symfony framework

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player