PHP attributes were introduced in PHP 8, providing a way to attach metadata to classes, methods, properties, and other PHP entities. They allow developers to add declarative metadata in the form of attributes to code elements.
Syntax: Attributes are represented by an @ symbol followed by the attribute name, optionally including parentheses for parameters.
#[MyAttribute]
#[MyAttribute(parameter)]
Defining Attributes: Attributes are defined as classes marked with the [Attribute]
suffix. These classes can have constructor parameters to pass additional data when applying the attribute.
#[Attribute]
class MyAttribute {
public function __construct(public $parameter) {}
}
Applying Attributes: Attributes are then placed directly on classes, methods, properties, etc., to specify metadata.
#[MyAttribute('some_parameter')]
class MyClass {
#[MyAttribute('another_parameter')]
public $myProperty;
#[MyAttribute('method_parameter')]
public function myMethod() {}
}
Retrieving Attributes: You can use reflection to retrieve attributes on classes, methods, or properties and evaluate their parameters or other information.
$classAttributes = #[MyAttribute] get_attributes(MyClass::class);
$propertyAttributes = #[MyAttribute] get_attributes(MyClass::class, 'myProperty');
$methodAttributes = #[MyAttribute] get_attributes(MyClass::class, 'myMethod');
PHP attributes offer a structured way to integrate metadata directly into code, which is especially useful for conveying information like validation rules, access controls, documentation tags, and more in a clearer and declarative manner. They also facilitate the use of reflection to retrieve this metadata at runtime and act accordingly.