🐘 PHP
Advanced
What are PHP Attributes?
Answer
Attributes (PHP 8.0) are structured, machine-readable metadata added to classes, methods, properties, function parameters, and constants using the #[AttributeName] syntax. They replace the docblock annotation workaround (e.g., /** @Route("/home") */) with native, type-safe metadata. Define a custom attribute: #[Attribute] class Route { public function __construct(public string $path) {} }. Apply it: #[Route("/home")] function index() {}. Read via Reflection: $method->getAttributes(Route::class)[0]->newInstance(). Symfony, Doctrine, and modern PHP frameworks use attributes for routing (#[Route]), entity mapping (#[ORM\Entity]), validation (#[Assert\NotBlank]), and DI configuration (#[Autowire]).