How to clone an array of objects in PHP?

后端 未结 15 669
鱼传尺愫
鱼传尺愫 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;
    }
    
    0 讨论(0)
  • 2020-12-13 17:38

    I've done it like this:

    function array_clone($array) {
        array_walk_recursive($array, function(&$value) {
            if(is_object($value)) {
                $value = clone $value;
            }
        });
        return $array;
    }
    

    The function arg copies the array without cloning the objects, then each nested object is cloned. So it won't work if the algorithm is not used inside a function.

    Note this function clone the array recursively. You can use array_walk instead of array_walk_recursive if you do not want this to happen.

    0 讨论(0)
  • 2020-12-13 17:38

    A pure PHP 7.4 >= solution:

    $cloned = array_map(fn ($o) => clone $o, $original);
    
    0 讨论(0)
  • 2020-12-13 17:39

    For PHP 5 and above one can use ArrayObject cunstructur to clone an array like the following:

    $myArray = array(1, 2, 3);
    $clonedArray = new ArrayObject($myArray);
    
    0 讨论(0)
  • 2020-12-13 17:41

    Objects are passed by pointed by default and are not always easy to clone especially as they may have circular references. You would be better suited with a different choice of data structures.

    For those providing solutions to shallow copy the easier way is this:

     $b = (array)$a;
    

    For deep copies I do not recommend this solution:

    $nuarr = json_decode(json_encode($array));

    This is for a deep copy. It only supports a subset of PHP types and will swap objects to array or arrays to objects which might not be what you want as well as potentially corrupting binary values and so on.

    If you make a manual recursive function for deep copies the memory usage will be much less afterwards for scalar values and keys so using json or any serializer an impact beyond its point of execution.

    It may be better to use unserialize(serialize($a)) for deep copies if performance is not a concern which has wider support for things such as objects though I would not be surprised if it breaks for circular references and several other unusual things.

    array_merge_recursive or array_walk_recursive can also be used for arrays.

    You can easily create your own recursive function that uses is_object and is_array to choose the appropriate means of copying.

    0 讨论(0)
  • 2020-12-13 17:47

    You need to clone objects to avoid having references to the same object.

    function array_copy($arr) {
        $newArray = array();
        foreach($arr as $key => $value) {
            if(is_array($value)) $newArray[$key] = array_copy($value);
            else if(is_object($value)) $newArray[$key] = clone $value;
            else $newArray[$key] = $value;
        }
        return $newArray;
    }
    
    0 讨论(0)
提交回复
热议问题