PHP › PHP 8 Features (Attributes, Enums, Match, Nullsafe Operator)

What are PHP attributes introduced in PHP 8, and how do they provide a structured, native alternative to the older convention of using docblock comments for metadata?

Intermediate

Answer

Attributes let you attach structured, machine readable metadata directly to a class, method, or property using a specific bracket based syntax, which can then be read and acted upon at runtime using PHP's reflection capabilities, providing a native, properly parsed alternative to the older convention of embedding similar metadata within docblock comments, which always required a separate, less reliable text parsing step to actually interpret.
#[Route('/users/{id}', methods: ['GET'])]
class UserController {
    public function show($id) {}
}
Real-world example A modern PHP framework uses attributes to define route mappings directly above controller methods, letting the framework's routing system reliably read this configuration through PHP's built in reflection capabilities rather than parsing potentially fragile docblock comments.

Common follow-ups: How do you read an attribute's data using PHP's reflection API at runtime?;What are common real world use cases for attributes in modern PHP frameworks?