PHPDoc: Documenting a function with a variable number of arguments

Wilco picture Wilco · Jan 25, 2013 · Viewed 12.3k times · Source

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

Maybe something like this?

<?php

class Foo {
    /**
     * Calculates the sum of all the arguments.
     *
     * @param mixed [$arg1, $arg2, ...]
     *
     * @return float the calculated sum
     */
    public static function sum() {
        return array_sum(func_get_args());
    }
}

Note: As a general rule, I imagine this type of thing should be avoided where possible. That being said, it would be nice to still document the remaining few cases where it cannot be avoided.

Answer

OnethingSimple picture OnethingSimple · Jul 9, 2016

If your using a variable number of arguments and also using PHP >= 5.6 then you are able to use variadic functions (allowing variable number of arguments) which still conforms to the PHPDoc ,... syntax already mentioned and PHPStorm will interpret the docs properly as well. Using variadic functions eliminates needing func_get_args() to capture arguments into an array.

/**
 * @param mixed $args,... Explainatorium!
 */
function variadiculous(...$args) {
    // NOTE: $args === func_get_args()
    foreach ( $args as $arg ) {
        /* do work */
    }
}

PHPStorm will auto-generate the docs as @param array $args because technically when inside the function variadiculous is_array($args) is true. I change it to read @param mixed $args,... as above and when I use the hotkey to display a function signature from somewhere else in my code PHPStorm displays variadiculous($args : ...array|mixed) -- I recommend using this method if your using PHP >= 5.6