Home / News / PHP Attributes: Modern Metadata in Your Code

PHP Attributes: Modern Metadata in Your Code

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.

Tagged:

Leave a Reply

Your email address will not be published. Required fields are marked *