PHP Inline type hinting in Eclipse

For the most part type hinting works pretty well using PDT in Eclipse. It speeds up coding and the best part is Eclipse will automatically determine variable types from class definitions and DocBlock comments. Eclipse also supports inline type hints for when it cannot determine a variable’s type, but the format is a little different than normal DocBlock comments and I always end up having to search for examples when I need it. So I leaving myself a reminder here and hopefully it will be helpful to someone else as well.

This usually comes up when I’m iterating through a list of objects…

foreach ($arrayOfObjects as $object) {
    $object->property;
    $object->method();
}

It would be nice if Eclipse could help me out with the properties and methods for $object, but it has no way of determining type type of $object. Inline type hinting to the rescue…

/* @var $object \My\Object */
foreach ($arrayOfObjects as $object) {
    $object->property;
    $object->method();
}

Now Eclipse will happily auto complete methods and properties for $object. The part I always forget is that this is not a DocBlock comment (one asterisk /* instead of two /**) and that the variable’s type comes after the variable’s name, which is the opposite of other PHPDoc tags. Eclipse is very particular about this and type hinting will not work if it’s not right. Another important thing to keep in mind is that types in comments must include the complete namespace including the leading slash.

Leave a Reply

Your email address will not be published. Required fields are marked *