🐘 PHP Advanced

What are PHP Attributes?

Why Interviewers Ask This

Senior PHP engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.

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]).

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a PHP codebase.