How to clone an array of objects in PHP?

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

    $a = ['a'=>'A','b'=>'B','c'=>'C'];
    $b = $a+[];
    $a['a'] = 'AA'; // modifying array $a
    var_export($a);
    var_export($b); 
    

    Result:

    array ( 'a' => 'AA', 'b' => 'B', 'c' => 'C', )
    array ( 'a' => 'A', 'b' => 'B', 'c' => 'C', )
    

提交回复
热议问题