PHP Variable-length argument lists


Example

5.6

PHP 5.6 introduced variable-length argument lists (a.k.a. varargs, variadic arguments), using the ... token before the argument name to indicate that the parameter is variadic, i.e. it is an array including all supplied parameters from that one onward.

function variadic_func($nonVariadic, ...$variadic) {
    echo json_encode($variadic);
}

variadic_func(1, 2, 3, 4); // prints [2,3,4]

Type names can be added in front of the ...:

function foo(Bar ...$bars) {}

The & reference operator can be added before the ..., but after the type name (if any). Consider this example:

class Foo{}
function a(Foo &...$foos){
    $i = 0;
    foreach($a as &$foo){ // note the &
        $foo = $i++;
    }
}
$a = new Foo;
$c = new Foo;
$b =& $c;
a($a, $b);
var_dump($a, $b, $c);

Output:

int(0)
int(1)
int(1)

On the other hand, an array (or Traversable) of arguments can be unpacked to be passed to a function in the form of an argument list:

var_dump(...hash_algos());

Output:

string(3) "md2"
string(3) "md4"
string(3) "md5"
...

Compare with this snippet without using ...:

var_dump(hash_algos());

Output:

array(46) {
  [0]=>
  string(3) "md2"
  [1]=>
  string(3) "md4"
  ...
}

Therefore, redirect functions for variadic functions can now be easily made, for example:

public function formatQuery($query, ...$args){
    return sprintf($query, ...array_map([$mysqli, "real_escape_string"], $args));
}

Apart from arrays, Traversables, such as Iterator (especially many of its subclasses from SPL) can also be used. For example:

$iterator = new LimitIterator(new ArrayIterator([0, 1, 2, 3, 4, 5, 6]), 2, 3);
echo bin2hex(pack("c*", ...$it)); // Output: 020304

If the iterator iterates infinitely, for example:

$iterator = new InfiniteIterator(new ArrayIterator([0, 1, 2, 3, 4]));
var_dump(...$iterator);

Different versions of PHP behave differently:

  • From PHP 7.0.0 up to PHP 7.1.0 (beta 1):
    • A segmentation fault will occur
    • The PHP process will exit with code 139
  • In PHP 5.6:
    • A fatal error of memory exhaustion ("Allowed memory size of %d bytes exhausted") will be shown.
    • The PHP process will exit with code 255

Note: HHVM (v3.10 - v3.12) does not support unpacking Traversables. A warning message "Only containers may be unpacked" will be shown in this attempt.