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 /** ... */):

    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").