指定数组索引类型

时间:2015-08-28 17:44:41

标签: php phpstorm phpdoc

如何指定数组索引和子索引类型? 注意:我会将它与PHPStorm一起使用。

数组示例

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

示例无效):

/**
 * @param array $options
 *      @var int   $length
 *      @var array $more
 *          @var bool $test1
 *          @var bool $test2
 */

2 个答案:

答案 0 :(得分:2)

一般来说,PhpStorm只支持简单的语法,就像Sam所说的那样,例如

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

上面描述的代码是字符串数组。

安装选项完成插件 - 它支持PHPDoc中哈希(描述数组键及其类型)的新建议语法:https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#7-describing-hashes

此插件将为数组键添加代码完成。

<?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

注意:这个插件的主要目的是提供数组键完成 - 我不确定它是否支持每个数组元素的类型分辨率(如果它们不同,如​​果它们不同)你的例子。)

答案 1 :(得分:0)

看起来,according to the docs,只能将数组定义为一个特定类型的集合(而不是为每个索引设置一个类型):

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

更好的解决方案可能是让$options成为一个类,因此lengthtest1可以是具有默认值和预定义类型的属性。