How to clone an array of objects in PHP?

后端 未结 15 668
鱼传尺愫
鱼传尺愫 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:49

    You need to loop it (possibly using a function like array_map() for that), there is no PHP function to automatically perform a deep copy of an array.

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

    Just include this function in all of your classes. This will do a deep clone of all objects in case if you have arrays of objects within the object itself. It will trigger all of the __clone() functions in these classes:

    /**
     * Clone the object and its properties
     */
    public function __clone()
    {
        foreach ($this as $key => $property)
        {
            if(is_array($property))
            {
                foreach ($property as $i => $o)
                {
                    if(is_object($o)) $this->$key[$i] = clone $o;
                    else $this->$key[$i] = $o;
                }
            }
            else if(is_object($property)) $this->$key = clone $property;
            else $this->$key = $property;
        }
    }
    
    0 讨论(0)
  • 2020-12-13 17:51

    I opted for clone as well. Cloning an array does not work (you could consider some arrayaccess implementation to do so for you), so as for the array clone with array_map:

    class foo {
        public $store;
        public function __construct($store) {$this->store=$store;}
    }
    
    $f = new foo('moo');
    $a = array($f);
    
    $b = array_map(function($o) {return clone $o;}, $a);
    
    $b[0]->store='bar';    
    var_dump($a, $b);
    

    Array clone with serialize and unserialize

    If your objects support serialisation, you can even sort of deep shallow copy/clone with a tour into their sleeping state and back:

    $f = new foo('moo');
    $a = array($f);
    
    $b = unserialize(serialize($a));
    
    $b[0]->store='bar';
    var_dump($a, $b);
    

    However, that can be a bit adventurous.

    0 讨论(0)
提交回复
热议问题