PHPDoc type hinting for array of objects?
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[]
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.
Netbeans hints:
You get code completion on $users[0]->
and for $this->
for an array of User classes.
/**
* @var User[]
*/
var $users = array();
You also can see the type of the array in a list of class members when you do completion of $this->...
To specify a variable is an array of objects:
$needles = getAllNeedles();
/* @var $needles Needle[] */
$needles[1]->... //codehinting works
This works in Netbeans 7.2 (I'm using it)
Works also with:
$needles = getAllNeedles();
/* @var $needles Needle[] */
foreach ($needles as $needle) {
$needle->... //codehinting works
}
Therefore use of declaration inside the foreach
is not necessary.
PSR-5: PHPDoc proposes a form of Generics-style notation.
Syntax
Type[]
Type<Type>
Type<Type[, Type]...>
Type<Type[|Type]...>
Values in a Collection MAY even be another array and even another Collection.
Type<Type<Type>>
Type<Type<Type[, Type]...>>
Type<Type<Type[|Type]...>>
Examples
<?php
$x = [new Name()];
/* @var $x Name[] */
$y = new Collection([new Name()]);
/* @var $y Collection<Name> */
$a = new Collection();
$a[] = new Model_User();
$a->resetChanges();
$a[0]->name = "George";
$a->echoChanges();
/* @var $a Collection<Model_User> */
Note: If you are expecting an IDE to do code assist then it's another question about if the IDE supports PHPDoc Generic-style collections notation.
From my answer to this question.