1

How can I specify an array index and sub-index type? Note: I will use it with PHPStorm.

Array example:

function name ($options) {
    // $options['length']        => integer
    // $options['more']          => array
    // $options['more']['test1'] => boolean
    // $options['more']['test2'] => boolean
}

Example (that not works):

/**
 * @param array $options
 *      @var int   $length
 *      @var array $more
 *          @var bool $test1
 *          @var bool $test2
 */
David Rodrigues
  • 12,041
  • 16
  • 62
  • 90

2 Answers2

2

In general, PhpStorm only support simple syntax, just as Sam has stated, e.g.

/**
 * @param string[] $options
 */

The code above described parameter which is array of strings.


Install Options completion plugin -- it supports new proposed syntax for hashes (describing array keys and its' types) in PHPDoc: https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#7-describing-hashes

This plugin will add code completion for array keys.

<?php
class Element {
    /**
     * Initializes this class with the given options.
     *
     * @param array $options {
     *     @var bool   $required Whether this element is required
     *     @var string $label    The display name for this element
     * }
     */
    public function __construct(array $options = array())
    {
        // some code here
    }
}


new Element(['label' => 'Bob', '|' ]);
//                              | Ctrl+Space will show supported attributes

NOTE: Main purpose of this plugin is to offer array keys completion -- I'm not sure how well it supports type resolutions for each of array elements (in case if they are different like in your example).

LazyOne
  • 158,824
  • 45
  • 388
  • 391
0

It looks like, according to the docs, that it's only possible to define an array as a set of one specific type (instead of setting a type for each index):

/**
 * @param string[] $options
 */

The better solution would probably be to make $options a class, so length and test1 could be properties with default values and pre-defined types.

Sam
  • 20,096
  • 2
  • 45
  • 71