使用splat操作符(..)时通过引用传递



我有两个函数。它们中的一个接收并修改通过引用传递的数组中的一些值。

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

另一个是类中的方法,它包装了第一个方法:

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

然而,如果我将数组传递给'foo',数组保持不变。我试图用&声明foo(... &$args),但这会导致语法错误。

在PHP中使用splat操作符时是否有一种通过引用传递参数的方法?

x版本https://3v4l.org/9ivmL

这样做:

<?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: $countrn";
print_r($values); //Expected [1,2,3,4]

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

参见:https://www.php.net/manual/en/functions.arguments.php示例#13

最新更新