PHP 8.0 introduced a vital feature called attributes. It is very similar to annotations available in other programming languages. Attributes are special tokens that allow structured metadata injection within classes, functions, and properties. In this tutorial, you will learn how to use PHP 8.0 attributes.

Why Use Attributes in PHP 8.0?

Attributes in PHP 8.0 facilitate the following key benefits:

  • Declarative Data Validation: You can use attributes to specify the expected data types declaratively instead of writing validation logic for each data input, making the validation process more intuitive.
  • Streamlined Middleware Management: By assigning specific attributes to methods or classes, you can improve middleware management, reduce manual configuration, and increase code readability.
  • Enhanced Dependency Injection: Instead of relying on external configuration or the factory pattern, you can use attributes for a more simplified and unified approach to managing dependencies within code. It enhances the visibility of relationships and dependencies between objects.
  • Semantic Mapping: You can use attributes for databases, external APIs, or other integrations. They enable PHP classes to link to external entities in a clear and easily understandable way.

Defining Attributes

Defining an attribute is simple in PHP 8.0. You must create a class with the #[Attribute] syntax. Here's an example:

class MyAttribute
    public function __construct(public string $value) {}

Applying Attributes

To use the attribute defined above, include it in a class or function in the following way:

#[MyAttribute('Example Value')]
class MyClass
    // Class code here

Built-in Attributes in PHP 8.0

PHP 8.0 also added predefined features to help developers handle specific usage scenarios. These built-in features are designed to meet specific needs, improve code clarity, and provide tools for better coding practices.

Attribute Description
#[Deprecated] Marks a function, class, or method as deprecated.
#[Pure] Indicates that a function does not change state.
#[JetBrains\PhpStorm\Immutable] Specifies that a class or method is immutable.
#[Required] Used in property promotion, it indicates a property is required in the constructor.

Accessing Attributes during Runtime

To access attributes during runtime, you can utilize the Reflection API. The following code snippet provides an example:

$reflectionClass = new ReflectionClass(MyClass::class);
$attributes = $reflectionClass->getAttributes();

The above code will generate an array containing all the attributes used in the class.


You can significantly enhance your PHP coding abilities by understanding how to define, use, and reflect attributes. PHP 8.0 attributes are a powerful and flexible way to annotate code, allowing you to enable various new functionalities explicitly.

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram