Search code examples
phpdocphp-8php-attributes

How to replace phpdocs with new attributes in php 8


I am using laravel. I need to know how phpdoc can be written in php 8 with attibutes.

/**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
      //Some code
      return [];
    }

Can someone please explain how the above code can be written with attributes.


Solution

  • I believe you have misunderstood what Attributes are for, and how they related to doc blocks. There are two common uses of doc blocks (comments marked with /** ... */):

    • To document the code (hence the name "doc block"), in a mostly-standardised way which can be read by various tools, including documentation generators and IDEs.
    • To add machine-readable annotations to the code, for use with libraries and frameworks that can automatically generate behaviour based on those. For instance, an ORM might use an annotation of @TableName('Foo') to link a class to a particular database table, and generate appropriate SQL.

    The example you've shown is of the first usage. What you have written is still the correct way of writing documentation (although see extra note below).

    PHP 8's native Attributes replace the second usage. It's up to the library what Attributes to look for, but an ORM that previously looked for @TableName('Foo') in a docblock might now look for #[TableName('Foo')] as a native Attribute instead.


    Unrelated to attributes, but worth noting, is that increasingly the type information from your documentation can be added as inline type declarations checked by PHP itself. For instance, the example in the question can be declared like this:

    public function toArray(\Illuminate\Http\Request $request): array
    {
        // ...
    }
    

    The doc block is still useful for adding descriptions (e.g. what will be in the returned array?), and type information not supported natively by PHP (e.g. @return SomeClassName[] meaning "returns a list of SomeClassName instances").