簡體   English   中英

使用 splat 運算符時按引用傳遞 (...)

[英]Pass by reference when using splat operator (...)

我有兩個功能。 其中之一接收並修改通過引用傳遞的數組中的某些值。

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

另一個是 class 中的一個方法,它包裝了第一個:

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

但是,如果我將數組傳遞給“foo”,數組將保持不變。 我試圖用&聲明foo(... &$args)但這導致了語法錯誤。

在 PHP 中使用 splat 運算符時,有沒有辦法通過引用傳遞 arguments?

對於 PHP 8.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: $count\r\n";
print_r($values); //Expected [1,2,3,4]

Output

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

請參閱: https://www.php.net/manual/en/functions.arguments.php示例 #13

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM