Programming Languages
PHP
Subjective
Sep 23, 2025
Explain PHP 8+ Attributes with a practical example. How do they differ from annotations and what are their performance implications?
Detailed Explanation
PHP Attributes (PHP 8.0+):
Practical Example - API Route Mapping:
#[Attribute(Attribute::TARGET_METHOD)]
class Route {
public function __construct(
public string $method,
public string $path,
public array $middleware = []
) {}
}
#[Attribute(Attribute::TARGET_PARAMETER)]
class Validate {
public function __construct(public string $rules) {}
}
class UserController {
#[Route("POST", "/users", ["auth", "throttle"])]
public function create(
#[Validate("required|email")] string $email,
#[Validate("required|min:8")] string $password
): User {
return User::create(compact("email", "password"));
}
}
// Attribute Processing
class RouteProcessor {
public function processController(string $className): array {
$reflection = new ReflectionClass($className);
$routes = [];
foreach($reflection->getMethods() as $method) {
$attributes = $method->getAttributes(Route::class);
foreach($attributes as $attribute) {
$route = $attribute->newInstance();
$routes[] = [
"method" => $route->method,
"path" => $route->path,
"handler" => [$className, $method->getName()],
"middleware" => $route->middleware
];
}
}
return $routes;
}
}
Differences from Annotations:
- Native Support: Built into PHP, no parsing needed
- Type Safety: Attributes are actual PHP classes
- Performance: Compiled into opcache, faster than docblock parsing
- IDE Support: Full autocompletion and refactoring
Performance Implications:
- Compile Time: Minimal overhead, cached in opcache
- Runtime: Only accessed via Reflection API when needed
- Memory: Stored efficiently in opcache metadata
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts