Attributes
suggest changeIntroduced in PHP 8.0, Attributes provide structured, machine-readable metadata that can be attached directly to classes, methods, functions, properties, parameters, and class constants. Prior to PHP 8, developers relied on unstructured PHPDoc docblock comments (such as @Route or @Inject) parsed via regular expressions. Attributes replace docblock annotations with native language syntax and compile-time validation.
1. Basic Syntax
Attributes use the #[...] syntax and can take optional arguments, including named arguments and constants:
<?php
#[Route('/api/users', methods: ['GET'])]
class UserController
{
#[Inject]
private UserService $userService;
#[Route('/{id}', methods: ['GET'])]
public function getUser(#[ValidateId] int $id): JsonResponse
{
// ...
}
}
2. Declaring Custom Attributes
A custom attribute is simply a standard PHP class marked with the #[Attribute] attribute:
<?php
namespace App\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class LogExecutionTime
{
public function __construct(
public readonly string $level = 'info',
public readonly int $thresholdMs = 100
) {}
}
Specifying Target Flags
By default, an attribute can be applied to any declaration. You can restrict where it may be placed using bitwise flags:
| Target Flag | Valid Placement |
|---|---|
Attribute::TARGET_CLASS |
Classes, interfaces, traits, and enums |
Attribute::TARGET_FUNCTION |
Global functions |
Attribute::TARGET_METHOD |
Class methods |
Attribute::TARGET_PROPERTY |
Class properties |
Attribute::TARGET_CLASS_CONSTANT |
Class constants |
Attribute::TARGET_PARAMETER |
Method and function parameters |
Attribute::TARGET_CONSTANT |
Global constants declared with const (PHP 8.5+) |
Attribute::TARGET_ALL |
Any target (default) |
Repeatable Attributes
By default, an attribute can only be applied once per target. To allow repeating the attribute, pass Attribute::IS_REPEATABLE:
<?php
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Middleware
{
public function __construct(public string $middlewareClass) {}
}
class DashboardController
{
#[Middleware(AuthMiddleware::class)]
#[Middleware(RateLimiter::class)]
public function index(): void {}
}
3. Reading Attributes with Reflection
Attributes are inspected at runtime using the Reflection API. Calling getAttributes() on any reflection target returns an array of ReflectionAttribute instances:
<?php
use App\Attributes\Route;
#[Route('/products', methods: ['GET'])]
class ProductController
{
#[Route('/{id}', methods: ['GET'])]
public function detail(int $id): string
{
return "Product detail for " . $id;
}
}
// Inspect class-level attributes
$reflector = new ReflectionClass(ProductController::class);
$attributes = $reflector->getAttributes(Route::class);
foreach ($attributes as $attr) {
// Instantiate the actual attribute object
$routeInstance = $attr->newInstance();
echo "Class Route Path: " . $routeInstance->path . "\n";
}
// Inspect method-level attributes
$methodReflector = $reflector->getMethod('detail');
$methodAttrs = $methodReflector->getAttributes(Route::class);
if (!empty($methodAttrs)) {
$route = $methodAttrs[0]->newInstance();
echo "Method Route: " . $route->path . "\n";
}
4. Built-in PHP Attributes
Modern PHP includes several powerful built-in attributes:
#[Override] (PHP 8.3+)
Ensures that a method with the same name exists in a parent class or implemented interface. If the parent method changes or is removed, PHP throws a compile error, preventing subtle refactoring bugs:
<?php
class BaseService
{
public function execute(): void {}
}
class CustomService extends BaseService
{
#[Override]
public function execute(): void
{
// Verified by the engine to override BaseService::execute
}
}
#[AllowDynamicProperties] (PHP 8.2+)
PHP 8.2 deprecated dynamic creation of undeclared class properties. Apply this attribute to classes that legitimately require dynamic properties (such as stdClass or legacy adapters):
<?php
#[AllowDynamicProperties]
class DynamicDataStore
{
}
$store = new DynamicDataStore();
$store->newProp = 'allowed without deprecation warning';
#[Deprecated] (PHP 8.4+)
Allows marking functions, methods, or class constants as deprecated natively:
<?php
class LegacyApi
{
#[Deprecated(message: "Use ApiV2::fetch() instead", since: "2.1.0")]
public function fetchOld(): void {}
}
5. Practical Example: Validation Engine
<?php
#[Attribute(Attribute::TARGET_PROPERTY)]
class Range
{
public function __construct(public int $min, public int $max) {}
}
class UserInput
{
#[Range(min: 18, max: 120)]
public int $age;
public function __construct(int $age)
{
$this->age = $age;
}
}
function validate(object $dto): array
{
$errors = [];
$reflector = new ReflectionObject($dto);
foreach ($reflector->getProperties() as $property) {
$rangeAttrs = $property->getAttributes(Range::class);
foreach ($rangeAttrs as $attr) {
$range = $attr->newInstance();
$val = $property->getValue($dto);
if ($val < $range->min || $val > $range->max) {
$errors[$property->getName()] = "Must be between {$range->min} and {$range->max}";
}
}
}
return $errors;
}
$input = new UserInput(15);
$errors = validate($input);
// ['age' => 'Must be between 18 and 120']