如何克隆在PHP对象的数组? [英] How to clone an array of objects in PHP?

查看:655
本文介绍了如何克隆在PHP对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的数组。我知道,物体得到由引用和数组由价值进行分配。但是,当我指定数组,数组的每个元素引用对象,所以当我要么数组中修改对象的变化反映在其他。

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 the object, so when I modify an object in either array the changes are reflected in the other.

有没有一种简单的方法来克隆一个数组,或者我必须依次通过它来克隆每个对象?

Is there a simple way to clone an array, or must I loop through it to clone each object?

推荐答案

引用当您复制的阵列已经被复制相同的对象。但是,这听起来像你想<击>浅拷贝深复制,当您创建第二个数组的第一个数组中被引用的对象,所以你得到不同但类似的对象的两个数组。

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;
}

这篇关于如何克隆在PHP对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆