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

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

As

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

Is equivalent

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

Do I need to duplicate this data?

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

Edit: I do not use PHPDoc to create my code documentation, but to maintain consistency in methods for me and my employees using PHPStorm.

+5
source share
2 answers

Docblock is something that an encoder can use to explain what a function does, it will be ignored by the PHP parser, as this is just a comment, it is good practice to put a docblock on each function and method, because when someone (or you) read the code, it's easier to see what the function does.

The IDE usually uses a dock block to autocomplete, however, the dock block will be overridden by string and :bool when the block does not match the code

but

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

NOT equivalent

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

In the first example :bool shows that foo() returns either true or false , something else, and PHP will try to apply a return to this type or cause a fatal error. Same thing with type string type for $text . The first parameter must be a value of type string, otherwise PHP will try to pass it to a string or a fatal error will be raised.

@return bool and @param string does nothing, it 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 problem, PHP can use 10 for 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 docblock makes the last one work (maybe it works even more with other problems because you are probably trying to do something with the PDO object)

Note. PHP does not yet support the mixed typehinting type (i.e. string | array), which still needs to be done by specifying it in docblock

+4
source

This is not necessary in PHP 7 because they are the same. If you have both, it may not actually synchronize if you later change it without changing the other.

Here you can find additional information https://wiki.php.net/rfc/scalar_type_hints_v5

+3
source

Source: https://habr.com/ru/post/1267334/


All Articles