Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPStorm + PHPdoc - can I type hint individual array element?

I have:

$myarr['DB'] = new DB();
$myarr['config'] = new config();

Can I make somehow PHPStorm to know what exactly inside thouse keys? For now I see only hinting fo variables and class properties, but not array keys.

like image 749
frenzy Avatar asked Sep 16 '15 14:09

frenzy


1 Answers

Late answer, but things have changed.

According to 2021.2 changelist it is possible now to define shape of a simple array with one line comment:

/**
 * @return array{id: int, name: string, object: \Of\Some\Class}
 */
function getArray(): array {...}

If there are object-like arrays in your code, you can now define their structure with this PHPDoc annotation: array{key: type, key: type, ...}.

PhpStorm provides code completion for such annotated arrays, reducing the time you spend on routine typing and protecting you from mistakes.

The support is limited to one-line array shape definitions. For larger structures, it is often better to use real objects and classes.

Unfortunatelly I have not found a way to define structure of multi dimensional array, and it would be great to annotate a list of such "shaped" arrays...

like image 143
SWilk Avatar answered Sep 23 '22 00:09

SWilk