'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.
Solution 1:[1]
You can define the array keys in advance, then PHPStorm will suggest them (CTRL+space)
$my = array();
$my['qwe'] = '';
$my['asd'] = '';
$my['zxc'] = '';
$my['']// inside '' will be autosuggest
You can also use phpdoc (CTRL+Q):
/**
* keys:
* <pre>
* some_array (array)
* some_bool (boolean)
* some_double (double)
* some_nice_integer (integer)
* </pre>
* @return array
*/
public function toArray(){
// return some array
}
Solution 2:[2]
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...
Solution 3:[3]
https://plugins.jetbrains.com/plugin/9927-deep-assoc-completion
Image from the plugin's github repo. I use the plugin and can confirm it performs as described.
Solution 4:[4]
This functional is not realized yet in PhpStorm. Vote for support array access feature request.
Also you can try silex idea plugin.
Solution 5:[5]
For an arbitrary array, PHPStorm has no idea of the keys that are used in any array, and thus does not provide hints there. It is even possible to proof that it is impossible to reliably implement such a feature, so I think you are out of luck here.
Collected From:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | j.steelman |
| Solution 4 | Onedev_Link |
| Solution 5 | Community |

