简体   繁体   中英

Pass by reference when using splat operator (...)

I have two functions. One of them receive and modify some values in an array that is passed by reference.

function dostuff ($param1, $param2, &$arr) {
    //...
    //add new elements to $arr
}

The other, which is a method in a class, that wraps the first one:

class Wrapper
{
    public function foo (...$args) {
        return dostuff(...$args);
    }
}

However, if I pass the array to 'foo', the array stays unchanged. I've tried to declare foo(... &$args) with an & but this led to an syntax error.

Is there a way to pass arguments by reference when using splat operator in PHP?

For PHP 8.x Versions https://3v4l.org/9ivmL

Do it like this:

<?php

class Wrapper
{
    public function foo (&...$args) {
        return $this->dostuff(...$args);
    }

    public function dostuff($param1, $param2, &$arr) {
        $arr[] = $param1;
        $arr[] = $param2;

        return count($arr);
    }
}


$values = [1,2];
$a=3;
$b=4;
$obj = new Wrapper();
#all parameter must be variables here because there are by ref now
$count = $obj->foo($a,$b, $values);

echo "Elements count: $count\r\n";
print_r($values); //Expected [1,2,3,4]

Output

Elements count: 4
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

See: https://www.php.net/manual/en/functions.arguments.php Example #13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM