PHPDoc: Typehint in nested arrays (with e.g. 2 dimensions)

14.3k views Asked by At

Is there a correct way to document values/objects in arrays which are within another dimension?

Normally an array will be handled like this:

/** @var ClassName[] $Array */
$Array = array( $InstanceOfClassName,.. )

But i need something like this:

/** @var ClassName[][] $Array */
$Array = array( 0 => array( $InstanceOfClassName,.. ) )

This is obviously not working, so what is the correct PHPDoc notation?

2

There are 2 answers

2
ashnazg On BEST ANSWER

First, understand that this usage of @var is not standard phpDocumentor spec. It is one of several different ways that different IDEs have tried to make "autocompletion for local variables" possible. I know that Eclipse uses the format /* @var $varName \ClassName */. So keep that in mind as other answers/suggestions come in.

The only way I can see to leverage this IDE autocompletion hack with your two dimensional array is to use another @var later on when you are reading the first dimension out, though this does require that to go into a variable itself:

/* @var $outer array */
$outer = array( 0 => array($InstanceOfClassName,...));

/* @var $inner ClassName[] */
$inner = $outer[0];

$inner[0]-> (expect autocompletion of ClassName methods here)

Now again, how useful this can be for autocompletion depends on how your IDE has built it. Some IDEs might know that ClassName[] syntax and deduce that an element pulled from $inner is a ClassName, and therefore it can show its methods. However, I cannot say I've seen any IDE do that yet. At most, it's been a stretch to see IDEs simply have the @var hack available in its most basic form (/* @var $var ClassName */).

TL;DR: Your mileage may vary in just trying to get half of what you're after :-)

3
lisachenko On

PhpStorm allows to typehint nested arrays with double brackets [][]:

/** @var \SplFileInfo[][] $doubleNestedArray */
$doubleNestedArray = [[]];

$doubleNestedArray[0][1]->getFileInfo(); // ->getFileInfo() is suggested by IDE