Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPDoc type hinting for array of objects?

So, in PHPDoc one can specify @var above the member variable declaration to hint at its type. Then an IDE, for ex. PHPEd, will know what type of object it's working with and will be able to provide a code insight for that variable.

<?php   class Test   {     /** @var SomeObj */     private $someObjInstance;   } ?> 

This works great until I need to do the same to an array of objects to be able to get a proper hint when I iterate through those objects later on.

So, is there a way to declare a PHPDoc tag to specify that the member variable is an array of SomeObjs? @var array is not enough, and @var array(SomeObj) doesn't seem to be valid, for example.

like image 659
Artem Russakovskii Avatar asked Apr 22 '09 18:04

Artem Russakovskii


2 Answers

In the PhpStorm IDE from JetBrains, you can use /** @var SomeObj[] */, e.g.:

/**  * @return SomeObj[]  */ function getSomeObjects() {...} 

The phpdoc documentation recommends this method:

specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.

Example: @return int[]

like image 154
Nishi Avatar answered Oct 06 '22 00:10

Nishi


Use:

/* @var $objs Test[] */ foreach ($objs as $obj) {     // Typehinting will occur after typing $obj-> } 

when typehinting inline variables, and

class A {     /** @var Test[] */     private $items; } 

for class properties.

Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:

The best you can do is say,

foreach ($Objs as $Obj) {     /* @var $Obj Test */     // You should be able to get hinting after the preceding line if you type $Obj-> } 

I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.

like image 27
Zahymaka Avatar answered Oct 05 '22 22:10

Zahymaka