How can arguments to variadic functions be passed by reference in PHP?

There is no way of passing variable length argument lists by reference in PHP. It is a fundamental limitation of the language.

There is, however, a workaround with array(&$var1, &$var2...) syntax:

<?php

/** raise all our arguments to the power of 2 */
function pow2() {
        $args = &func_get_arg(0);

        for ($i = 0; $i< count($args); ++$i) {
            $args[$i] **= 2;
        }
}


$x = 1; $y = 2; $z = 3;
pow2(array(&$x, &$y, &$z)); // this is the important line

echo "$x, $y, $z"; // output "1, 4, 9"

Test could also be declared function test($args) but I wanted to illustrate that this works with the func_get_args() family of functions. It is the array(&$x) that causes the variable to be passed by reference, not the function signature.

From a comment on PHP's documentation on function arguments: http://php.net/manual/en/functions.arguments.php


As of PHP 5.6 you can pass arguments by reference to a variadic function. Here's an example from the RFC:

public function prepare($query, &...$params) {
    $stmt = $this->pdo->prepare($query);
    foreach ($params as $i => &$param) {
        $stmt->bindParam($i + 1, $param);
    }
    return $stmt;
}