doqrjrc95405 2015-09-01 09:07
浏览 44

PHP变量赋值被视为引用

We have the following code:

$fruits = array(
    (object) array(
        'name' => 'orange',
        'country' => 'brazil',
        'qty' => 23,
        'destination' => 'romania'
    ),
    (object) array(
        'name' => 'pinapple',
        'country' => 'thailand',
        'qty' => 3,
        'destination' => 'germany'
    ),
    (object) array(
        'name' => 'carrot',
        'country' => 'romania',
        'qty' => 250,
        'destination' => 'france'
    ),
    (object) array(
        'name' => 'bannana',
        'country' => 'kenya',
        'qty' => 50,
        'destination' => 'sweden'
    ),
    (object) array(
        'name' => 'melon',
        'country' => 'romania',
        'qty' => 50,
        'destination' => 'uae'
    )
);

function testing($fruits)
{
    for($i = 0, $size = sizeof($fruits); $i < $size; $i++)
    {
        $fruit = $fruits[$i];
        $fruits[$i]->qty = $fruit->qty * 100;

        unset($fruit->destination);
        unset($fruit->test);
        unset($fruit->country);
    }

    return $fruits;
}

var_dump($fruits);

testing($fruits);

var_dump($fruits);

?>

If you run that code, the $fruits array has its items changed since it's passed as reference.

The question is: how can we pass it so that the testing() function does not alter the $fruits?

Thanks to all.

  • 写回答

1条回答 默认 最新

  • doujieju0397 2015-09-01 09:11
    关注

    What about cloning your objects ?

    $clone = array();
    
    foreach ($fruits as $k => $v) {
        $clone[$k] = clone $v;
    }
    testing($clone);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大