1 min read

PHP Attributes (Annotations)

Attributes (also known as annotations in other languages) offer a mechanism to add structured, machine-readable metadata declarations to your code. They were introduced in PHP 8.0.

Attributes can be applied to classes, methods, functions, parameters, properties, and class constants.


1. Syntax

Attributes are enclosed in hash-brackets #[ ... ].

#[Attribute]
class MyAttribute {
}

#[MyAttribute]
class MyClass {
}

2. Defining Custom Attributes

To create an attribute, you simply create a class and mark it with the #[Attribute] attribute itself.

#[Attribute]
class Route {
    public $path;
    public $method;

    public function __construct($path, $method = 'GET') {
        $this->path = $path;
        $this->method = $method;
    }
}

3. Applying Attributes

You can pass arguments to the attribute constructor when applying it.

#[Route('/home', method: 'GET')]
function home() {
    // ...
}

4. Reading Attributes (Reflection)

Attributes don't do anything by themselves. You use the Reflection API to read them at runtime.

$reflection = new ReflectionFunction('home');
$attributes = $reflection->getAttributes(Route::class);

foreach ($attributes as $attribute) {
    $route = $attribute->newInstance();
    echo $route->path; // Outputs: /home
}

programming/php/php programming/php/php-reflection