Yo, PHP 8 got ‘attributes’! π₯
Now, you can add metadata directly to classes, methods, or properties like annotations in Java or decorators in Python.
π¬ What are attributes?
Attributes in PHP 8 are just classes marked with #[Attribute]
π€
use Attribute;
#[Attribute]
class Route {
public function __construct(
public string $path,
Since PHP 8, weβve had attributes β a modern way to add metadata directly to classes, methods, or properties. Think of them like annotations in Java or decorators in Python.
π What are attributes?
Attributes let you βtagβ parts of your code with extra information. Frameworks or libraries can then read these tags at runtime and act on them.
Example:
#[Route('/home', methods: ['GET'])]
class HomeController {
// ...
}
Here, the Route
attribute describes how this controller should be exposed.
βοΈ How do you define an attribute?
Attributes are just classes marked with #[Attribute]
.
use Attribute;
#[Attribute]
class Route {
public function __construct(
public string $path,
public array $methods = ['GET']
) {}
}
π How to read attributes with Reflection
You can fetch and use attributes at runtime via the Reflection API:
$reflection = new ReflectionClass(HomeController::class);
// Get all attributes on the class
foreach ($reflection->getAttributes(Route::class) as $attr) {
// Turn attribute into a real object
$route = $attr->newInstance();
echo $route->path; // "/home"
echo implode(',', $route->methods); // "GET"
}
This is how frameworks like Symfony or Doctrine process metadata and apply logic automatically.
β
Why use attributes?
- Cleaner than PHPDoc comments
- More flexible than marker interfaces
- Supported natively by PHP, no hacks needed
ποΈ Where are they used?
-
Symfony β
#[Route]
for controllers
-
Doctrine ORM β
#[Entity]
, #[Column]
for database mapping
- Custom apps β logging, caching, validation rules
π In short: Attributes bring structured, modern metadata to PHP. Theyβre concise, powerful, and built right into the language β and with reflection, they let your code adapt based on annotations.