PHP - PHP Attributes (Annotations Replacement)

PHP Attributes are a modern feature introduced in PHP 8 that allow developers to attach structured metadata directly to classes, methods, properties, parameters, and constants. They serve as a native replacement for traditional docblock annotations, which were previously written as comments and parsed manually by frameworks or libraries.

1. Background and Need

Before attributes were introduced, developers used doc comments (annotations) like:

/**
 * @Route("/home")
 * @Method("GET")
 */

These annotations were not part of the PHP language itself. They were simply comments, and frameworks such as Symfony or Doctrine had to parse them using reflection and custom logic. This approach had several drawbacks:

  • No syntax validation by PHP

  • Prone to human error

  • Required external parsers

  • Slower performance due to string parsing

Attributes solve these issues by making metadata a first-class feature of the language.


2. Basic Syntax

Attributes use the #[...] syntax and are placed directly above the declaration they apply to.

Example:

#[Route('/home', methods: ['GET'])]
function home() {
    echo "Welcome";
}

Here, Route is an attribute that can carry structured data like parameters.


3. Defining Custom Attributes

Attributes themselves are classes marked with a special #[Attribute] declaration.

Example:

#[Attribute]
class Route {
    public string $path;
    public array $methods;

    public function __construct(string $path, array $methods = []) {
        $this->path = $path;
        $this->methods = $methods;
    }
}

This defines a custom attribute that can be reused across the application.


4. Applying Attributes

Attributes can be applied to different parts of a program:

  • Classes

  • Methods

  • Properties

  • Function parameters

  • Constants

Example:

#[Entity]
class User {

    #[Column(type: "string")]
    public string $name;

    #[Column(type: "integer")]
    public int $age;
}

This is commonly used in ORM systems like Doctrine.


5. Reading Attributes Using Reflection

Attributes are accessed at runtime using PHP’s Reflection API.

Example:

$reflection = new ReflectionMethod('UserController', 'home');
$attributes = $reflection->getAttributes();

foreach ($attributes as $attribute) {
    $instance = $attribute->newInstance();
    print_r($instance);
}

This allows frameworks to dynamically read metadata and act accordingly.


6. Attribute Targets and Restrictions

You can restrict where an attribute can be used by specifying targets:

#[Attribute(Attribute::TARGET_METHOD)]
class Route {
}

Possible targets include:

  • TARGET_CLASS

  • TARGET_METHOD

  • TARGET_PROPERTY

  • TARGET_PARAMETER

  • TARGET_ALL

This improves correctness by preventing misuse.


7. Built-in Attributes

PHP also provides some built-in attributes such as:

  • #[Deprecated] – marks code as outdated

  • #[Override] – ensures method overrides a parent method (PHP 8.3+)

  • #[ReturnTypeWillChange] – helps during migration to strict typing

These improve code safety and maintainability.


8. Advantages of Attributes

  • Native language support with syntax validation

  • Better performance compared to parsing comments

  • Structured and type-safe metadata

  • Cleaner and more readable code

  • Easier integration with frameworks


9. Real-World Use Cases

Attributes are widely used in modern PHP frameworks for:

  • Routing (mapping URLs to functions)

  • Dependency injection configuration

  • ORM mapping (database relationships)

  • Validation rules

  • Access control and security policies

Example in a controller:

#[Route('/login', methods: ['POST'])]
#[Authorize(role: 'admin')]
function login() {
}

10. Comparison with Annotations

Aspect Annotations (Old) Attributes (New)
Type Comments Native syntax
Validation No Yes
Performance Slower (parsing needed) Faster
Tooling Support Limited Strong
Error Handling Weak Strong

Conclusion

PHP Attributes represent a major evolution in how metadata is handled in PHP. By replacing fragile comment-based annotations with a robust, language-supported mechanism, attributes improve code reliability, readability, and performance. They are now a core part of modern PHP development, especially in frameworks and enterprise applications.