tags:

views:

272

answers:

5

I have this code:

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
}

How can I accomplish this?

+6  A: 

well, you simply clone your object.

Anti Veeranna
A: 

Use a copy constructor.

Zed
A: 

Question 1: The for each loop by defualt should make a local copy of the value into your '$k=>$object' - any changes local to that foreach. Putting an '&' would pass it by reference instead of by value. Manual

Question 2: Can you var_dump the object? It make be casting your object in the foreach into an array or string - if the var_dump shows such, you are calling a method on a string.

Robert DeBoer
A: 

Either using the clone construct or looping through the object to assign it to the secondary.

Jon Ursenbach
A: 

You do not have to clone it, because you cannot change the members of an Iterable in a foreach loop. So when you do something like

$configObject->name = "whatever";

it will not have any effect on $this-> configObjects by default.

Quote from the PHP page:

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.

FlorianH
I'm not sure if this is applicable to php 5 as well or not
Click Upvote