Introduced in PHP 8.0, attributes provide a structured way to add metadata to your code declarations. They replace the docblock comments traditionally used for this purpose.
Basic Attribute Syntax
#[Attribute]
class Route {
public function __construct(
public string $path,
public string $method = 'GET'
) {}
}
#[Route('/products', 'GET')]
class ProductController {
#[Route('/{id}', 'GET')]
public function show(int $id) {}
}
Reading Attributes with Reflection
$reflectionClass = new ReflectionClass(ProductController::class);
$attributes = $reflectionClass->getAttributes();
foreach ($attributes as $attribute) {
$route = $attribute->newInstance();
echo "Path: " . $route->path . "\n";
echo "Method: " . $route->method . "\n";
}
Common Use Cases
- Routing: Define API endpoints
- Validation: Add validation rules to properties
- ORM mapping: Map classes to database tables
- Serialization: Control how objects are serialized
- Dependency Injection: Mark injectable services
Attribute Targets
You can restrict where attributes can be used:
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class MyAttribute {}
Built-in PHP Attributes
PHP includes several useful attributes:
#[Deprecated("Use newMethod() instead")]
#[AllowDynamicProperties]
#[ReturnTypeWillChange]
Attributes provide a cleaner, more maintainable approach to metadata than docblock comments, with proper syntax validation and IDE support.
