Search code examples
phpannotationsphp-attributes

How are PHP attributes different from doc block annotations?


Lately, the attributes RFC has passed the voting stage. How they are different from DocBlock annotations, and what benefits will they bring?

Consider simple Doctrine entity, before:

/**
 * @ORM\Entity
 */
class Entity {
    // …
}

After, using native PHP attributes:

#[ORM\Entity]
class Entity {
    // …
}

Solution

  • The explanation at this part of the RFC: Why not extending Doc Comments? explains a lot of the benefits

    • Namespacing prevents conflicts between different libraries using the same doc comment tag
    • Checking for attribute existence is a O(1) hash key test compared to unpredictable strstr() performance or even parsing the docblock.
    • Mapping attributes to classes ensures the attributes are correctly typed, reducing a major source of bugs in reliance on docblocks at runtime.
    • There is visible demand for something like annotations based on its common use in so many different tools and communities. However, this will always be a confusing thing for newcomers to see in comments. In addition, the difference between /* and /** is still a very subtle source of bugs.

    A lot of these boil down to the fact that attributes can be checked by PHP. Tools can leverage the fact that these attributes are already-parsed metadata visible with reflection, rather than comments that need to be parsed with a custom syntax per tool. IDEs and static analysis tools will be able to guarantee correctness without having to know a specific tool's docblock annotation syntax because the attributes resolve to classes that have to exist and might have further type annotations to add checking.

    So:

    • tools that define attributes that they use will benefit from correctness and performances gains because PHP will handle the parsing of these attributes for them
    • tools that analyze PHP will benefit from the easier type-checking guarantees and standards for checking attributes' correctness
    • humans will benefit from these tools' improvements and the fact that documentation and metadata can be better separated