How to clone an array of objects in PHP?

后端 未结 15 729
鱼传尺愫
鱼传尺愫 2020-12-13 17:00

I have an array of objects. I know that objects get assigned by \"reference\" and arrays by \"value\". But when I assign the array, each element of the array is referencing

15条回答
  •  臣服心动
    2020-12-13 17:37

    References to the same objects already get copied when you copy the array. But it sounds like you want to shallow-copy deep-copy the objects being referenced in the first array when you create the second array, so you get two arrays of distinct but similar objects.

    The most intuitive way I can come up with right now is a loop; there may be simpler or more elegant solutions out there:

    $new = array();
    
    foreach ($old as $k => $v) {
        $new[$k] = clone $v;
    }
    

提交回复
热议问题