Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using PHP7, is it necessary to document methods with PHPDoc?

Tags:

In PHP7, when a method sets a given parameter type and result type, is it necessary to document them again in the PHPDoc ?

Since

function foo(string $text): bool {     return true; } 

Is equivalent to

/**  * @param string $text  * @return bool  */ function foo($text) {     return true; } 

Is it necessary to duplicate these informations ?

/**  * @param string $text  * @return bool  */ function foo(string $text): bool {     return true; } 

Edit : I don't use PHPDoc to generate my code's documentation, but to maintain a consistency in the methods for me and my coworkers with the help of PHPStorm.

like image 562
Marc Brillault Avatar asked Apr 30 '17 20:04

Marc Brillault


1 Answers

The docblock is something that a coder can use to explain what a function does, it will get ignored by the PHP parser (see Edit below), as it is just a comment it is a good practice to put a docblock above every function and method, because when someone (or you) read the code it is easier to see what the function does.

A IDE usually uses the docblock to for autocomplete, the docblock will however be overridden by the string and :bool when the block doesn't match the code

However

function foo(string $text): bool {     return true; } 

Is NOT equivalent to

/**  * @param string $text  * @return bool  */ function foo($text) {     return true; } 

The :bool in the first example enforces that foo() returns either true or false, anything else and PHP will try to cast the return to that type or throw a fatal error. It is the same with the typehint string for $text. The first parameter must be a value of type string, otherwise PHP tries to casts it to a string or a fatal error will be thrown

The @return bool and @param string enforces nothing at all, just says that the expected return is either true or false

Take the following example:

function foo(string $a) :bool {     var_dump($a); // string '10'     return "string"; }  var_dump(foo(10)); // bool true 

No problems there, PHP can cast 10 to a string and "string" is true There is a problem with the following though

function foo(PDO $a) :bool  {     var_dump($a);     return "string"; }  var_dump(foo(10)); // fatal error, 10 is not PDO and can not be cast to PDO 

Using the docblock will make the last one work(probably running into other problems further on because you are probably trying to do something with a PDO object)

Note: PHP does not yet have support for mixed type typehinting (ie string|array) that still has to be done by specifing it in a docblock

EDIT:
As @inwerpsel pointed out in the comments, my statement that a docblock is ignored by PHP parser is incorrect. A docblock can be read in during runtime by the ReflectionClass.

like image 153
Jelmergu Avatar answered Oct 11 '22 03:10

Jelmergu