12
Lately I have come across some snippets of code that I can’t understand their purpose, are usually used within comments, which doesn’t make much sense to me.
Doing research on this subject falls in the term attributes, but even after that I couldn’t quite understand their reason. The use of the term attributes to refer to variables also hinders a lot in the search.
On the official website of PHP, in addition to other definitions, I understood that it is not something exclusive of PHP and that in fact it is very common.
Similar Concepts exist in other Languages named Annotations in Java, Attributes in C#, C++, Rust, Hack and Decorators in Python, Javascript.
An example of code:
/**
* @Route("/api/posts/{id}", methods={"GET", "HEAD"})
*/
class User
{
That in version 8.0 of PHP is
#[Route("/api/posts/{id}", methods: ["GET", "HEAD"])]
class User
{
Or even the extension I use to generate the getters and setters automatically:
/**
* Set the value of name
*
* @return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
In the latter case I always end up deleting these attributes.
What is their function? Are they necessary/fundamental or is soh something else to help compile/maintain the code? Should I always use them?
Symfony Framework used to use docblock, since PHP did not have native attribute support. I believe that in-house docblock was used
ReflectionFunctionAbstract::getDocComment
to extract that information and make it a functional part of the code. Currently, with the implementation of PHP 8, you also need to use Reflection to get this data, but without the need to parse docblock’s string.– Wallace Maxters
the
@return self
is used by the code editor to allow use of the autocomplete function– Pedro Sanção