Ali
Ali

Reputation: 267077

How to copy an object by value / clone an object in PHP 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?

Upvotes: 0

Views: 1847

Answers (5)

Anti Veeranna
Anti Veeranna

Reputation: 11583

well, you simply clone your object.

Upvotes: 6

FlorianH
FlorianH

Reputation: 3102

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.

Upvotes: 0

Jon Ursenbach
Jon Ursenbach

Reputation: 3192

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

Upvotes: 0

Robert DeBoer
Robert DeBoer

Reputation: 1695

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.

Upvotes: 0

Zed
Zed

Reputation: 57658

Use a copy constructor.

Upvotes: 1

Related Questions