Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP type hinting - code vs. annotations

PHP 5 can do some (limited) type hinting, however, it seems to me that in real-world projects, types are usually described in doc comments. For example, instead of this:

/**
 * Test method
 */
function test(SomeType $param1) {
    ...
}

there will more commonly be

/**
 * Test method
 *
 * @param SomeType param1
 */
function test($param1) {
    ...
}

What are the advantages and disadvantages of the two approaches? And if I'm right in the assumption that the PhpDoc method is more common, why is that? Why don't people utilize the built-in language feature more?

Edit: the third option is to use both approaches combined:

/**
 * Test method
 *
 * @param SomeType param1
 */
function test(SomeType $param1) {
    ...
}

However, I personally haven't seen this used too often (looked at libraries like Symfony or PHPUnit) and this also seems like doing some work for not much additional benefit to be honest. Maybe that's why it isn't seen more often.

like image 203
Borek Bernard Avatar asked Dec 19 '14 10:12

Borek Bernard


2 Answers

First thing: PHP typehints have different ability to hint than PHPDoc. Differences are (at least):

  • Scalar types. Before PHP 7.1, you can not hint scalar types, while nothing prevents you from hinting

    /**
     * @param string $param Param description
     */
    
  • Array of hinting. In PHPDoc you can hint, that parameter (or return value) is array of something. It would be:

    /**
     * @param ClassName[] $param Param description
     */
    

    and meaning of this is - array of instances of ClassName. This is extremely useful when it comes to return type (because IDE then may do substitutions for methods on iteration of that array, and, therefore, you'll know that you're doing correct thing or not). However, in PHP you can only typehint it as

    function functionName(array $param) { /*...*/ }
    

    so it won't be possible to realize what are actual elements of array. For your information there is a corresponding RFC for typehinting as array of some elements, which is currently rejected - but may be in future such possibility will appear in PHP.

But, on the other hand, using PHP typehints is still different thing and normally you should do both - so, if it's possible to hint somehow in PHP (like for array sample above) - do it, and add PHPDoc block as well. PHP typehint allows you to enforce behavior on language level, while PHPDoc is only "information" source, it serves only information goal and can not prevent of passing illegal argument type.

like image 79
Alma Do Avatar answered Sep 27 '22 19:09

Alma Do


Personally I would use both.

First option is good for controling what objects are you passing to the method. Second usually can be added automaticaly by any modern IDE and it makes your code more readable.

like image 21
gellu Avatar answered Sep 27 '22 21:09

gellu