Creating Custom Attributes in PHP 8: A Guide

Gabriel Anhaia
Dev Warlocks
Published in
4 min readAug 14, 2023

--

PHP has always been a dynamic language, evolving with the needs of developers and the web. With the release of PHP 8, the language introduced a powerful feature called "Attributes" (also known as "Annotations" in other languages). This feature allows developers to add metadata to classes, methods, properties, and function parameters.

In this article, we'll dive deep into how you can create your custom attributes in PHP 8, enhancing your codebase with expressive metadata.

What are Attributes?

Attributes provide a way to add metadata to your code. They are similar to docblocks but are structured and can be retrieved at runtime using PHP's reflection API. This makes them more versatile and powerful than simple comments.

The History of Attributes: From Annotations to PHP 8

The concept of adding metadata directly to code isn't new and has its roots in various programming languages under the name "annotations." Let's take a brief journey through the history of this concept.

Java and Annotations: Java was one of the first mainstream languages to introduce annotations, which it did with its Java 5 release in 2004. In Java, annotations allow developers to provide metadata about the code without…

--

--

Gabriel Anhaia
Dev Warlocks

Software Engineer (Billie GmbH), Freelancer, and Author. Germany/Brazil. Book Design Patterns em PHP: https://goo.gl/NNDZqe