Search code examples
phpphpdoc

Rely on PHPDoc or not? Is there any better type hinting?


I have run in multiple situations where I want autocompletion badly, but only way to specify type of class is to write PHPDoc. Does this approach just smell bad, or I can encounter some serious problems in the future? Here is the code that needs PHPDoc:

    /** @var genericTruck $pageObject */
    $pageObject = new $pageClass();

    echo $pageObject->drive();

$pageClass is string and can contain class name that is inherited from genericTruck class. Then I need to call methods from that superclass

    /** @var truckViewModel $model */
    foreach ($this->view as $model)
    {
        echo "<tr>
                <td>$model->name</td>
                <td><img src='$model->photo'/></td>
            </tr>";
    } 

Here $this->view is an array, where truckViewModel instances where put by array_push in another class method.


Solution

  • This is exactly how you should do it. In the case of $pageObject where it is a variable type, you should hint a common ancestor or interface that all types would extend or implement.

    I'm unsure that genericTruck follows class naming convention standards the best it can (should be Generic_Truck or GenericTruck etc as per most guidelines), but that's your decision.

    There is nothing weird or fishy about relying on PHPDoc for type hinting or guidelines. It's common practice to use it and it's not going away any time soon.