PHP 8: Modern PHP Development · Object-Oriented PHP 8
Attributes
Add structured metadata to classes and methods and read it with Reflection.
Attributes (8.0) are native, structured metadata written as #[Name(args)], replacing docblock annotations. Frameworks use them for routing (#[Route]), validation, ORM mapping (Doctrine), dependency injection and serialization. You define an attribute as a class marked with #[Attribute], then read it via Reflection. PHP ships built-ins such as #[\Override] (8.3), #[\SensitiveParameter] (8.2) and #[\Deprecated] (8.4).
<?php
#[Attribute(Attribute::TARGET_METHOD)]
final class Route
{
public function __construct(public string $method, public string $path) {}
}
final class OrderController
{
#[Route('GET', '/orders/{id}')]
public function show(int $id): Response { /* ... */ }
}
// Build a route table via reflection
foreach ((new ReflectionClass(OrderController::class))->getMethods() as $method) {
foreach ($method->getAttributes(Route::class) as $attr) {
$route = $attr->newInstance();
$router->add($route->method, $route->path, [OrderController::class, $method->name]);
}
}
function login(string $user, #[\SensitiveParameter] string $password) { /* hidden in stack traces */ }
Common pitfalls
- Attributes aren't validated until
newInstance()is called — test that they're read correctly. - Reflection at runtime on every request is slow; frameworks cache the results.
- Forgetting the leading backslash for built-ins inside namespaces (
#[\Override]).
Key points
- Attributes replace docblock annotations
- Read them with Reflection and cache the result
- Built-ins: Override, SensitiveParameter, Deprecated
Further reading: PHP manual: attributes
Practice questions
What does #[\Override] do?
Answer
It declares that a method is meant to override a parent or interface method. If no such method exists (e.g., after a rename upstream), PHP throws a compile-time error, catching silent bugs.
Why use #[\SensitiveParameter]?
Answer
It redacts that argument's value from stack traces and backtraces, preventing passwords or secrets from leaking into logs and error pages.
Open in the app to mark lessons complete, take notes and track your progress.