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

泄露秘密 提交于 2020-01-13 08:06:14

问题


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?


回答1:


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 :-)




回答2:


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

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

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


来源:https://stackoverflow.com/questions/20543050/phpdoc-typehint-in-nested-arrays-with-e-g-2-dimensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!