【问题标题】:Specify an array index type [duplicate]指定数组索引类型[重复]
【发布时间】:2015-11-23 11:02:47
【问题描述】:

如何指定数组索引和子索引类型? 注意:我会将它与 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
 */

【问题讨论】:

    标签: php phpstorm phpdoc


    【解决方案1】:

    一般来说,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
    

    注意:这个插件的主要目的是提供数组键补全——我不确定它对每个数组元素的类型解析支持的程度(如果它们不同,比如你的例子)。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2021-06-19
        • 2023-03-17
        • 2011-05-02
        • 2019-05-26
        • 2010-10-28
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        相关资源
        最近更新 更多