PHPDoc: Documenting a function with a variable number of arguments

前端 未结 4 1965
渐次进展
渐次进展 2021-01-07 16:57

What is the recommended method for documenting a class method that accepts a variable number of arguments?

Maybe something like this?



        
4条回答
  •  情书的邮戳
    2021-01-07 17:11

    Something worth noting is that with a doc block such as:

    /**
     * @param Type[] ...$values One or more values.
     */
    public function func(Type ...$values) {
        // ...
    }
    

    ...it might seem like you could pass an array of Type, e.g.

    Foo()->func([Type, Type, Type])
    

    ...this throws a fatal error, obviously now.

    Where:

    Foo()->func(...[Type, Type, Type])
    

    ...does not as you have destructured it on method call.

    Anyway the point here is that I was experimenting with how PHPStorm would treat the doc block and depending on the way in which you orient your $args variable in your doc block, with either ...$args or $args,... determines the type of hints you get back in your IDE.

    I'd really like a way to suggest the values you should pass by name into the method in the exemplified image below in the case where you have an optional length of function/method parameters, with a specific order in which they should be passed.

    You might think, "just set default args, $arg1 = 'default', $arg2 = true" which typically makes sense but in cases

    Pseudo-example:

    /**
     * @param int ...$args Hour, Minute, Second, Timezone, $arg [, ...$args]
     */
    public static function createA(int ...$args) {}
    
    /**
     * @param int $args,... Hour, Minute, Second, Timezone, $arg [, ...$args]
     */
    public static function createB(int ...$args) {}
    
    /**
     * @param int[]|int $args,... Hour, Minute, Second, Timezone, $arg [, ...$args]
     */
    
    public static function createC(int ...$args) {}
    

    ...so either of:

    • https://stackoverflow.com/a/38275992/1290575
    • https://stackoverflow.com/a/43622600/1290575

    ...is the correct answer (just keeping in mind orientaton: ...$args or $args,...)

提交回复
热议问题