Home > database >  Pass by reference when using splat operator (...)
Pass by reference when using splat operator (...)

Time:01-18

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?

CodePudding user response:

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

  • Related