Search code examples
phpphpstormphpdoc

PHPStorm + PHPDoc — Can I type-hint an individual array element?


I have:

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

Can I somehow make PhpStorm to know exactly what is inside those keys? For now I see hinting for variables and class properties only, but not array keys.


Solution

  • 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...