0

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?

5 Answers 5

6

well, you simply clone your object.

Sign up to request clarification or add additional context in comments.

Comments

1

Use a copy constructor.

Comments

0

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.

Comments

0

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

Comments

0

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.