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

这一生的挚爱 提交于 2019-12-01 03:13:52

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 "2, 4, 6"

?>

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!