2009-08-25 114 views
0

我有这样的代码:如何按值复制对象/克隆对象在PHP 5

foreach ($this->configObjects as $k=>$object) 
{ 
    $configObject=$object; 

    //Here I will make a lot of changes to $configObject, however 
    // I want all those changes to be kept only to the local copy of $configObject, 
    // So the next time this foreach loop is run $this->configObjects array will contain 
    // a clean slate of configObject objects which don't have any traces of any 
    // earlier changes that were made to them 
} 

我怎样才能做到这一点?

回答

6

好吧,你只需clone你的对象。

1

使用复制构造函数。

0

问题1:for each loop by defualt应将值的本地副本放入'$ k => $ object'中 - 任何局部变化的foreach。把'&'通过引用而不是按值传递。 Manual

问题2:你可以var_dump对象吗?它会将你的对象在foreach中转换为数组或字符串 - 如果var_dump显示这样的结果,那么你正在调用一个字符串的方法。

0

使用克隆构造或循环通过对象将其分配给辅助。

0

您不必克隆它,因为您无法在foreach循环中更改Iterable的成员。所以当你做类似

$configObject->name = "whatever"; 

默认情况下它不会对$ this-> configObjects有任何影响。从PHP page

报价:

注:除非数组是被引用,foreach指定数组的一个拷贝,而不是该数组本身运行。

+0

我不确定这是否适用于PHP 5以及不 – 2009-08-26 01:29:53