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

    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: