There is such code:

$r2 = array(); for($i = 0; $i < count($r); $i++) {//$r это массив объектов Room $rt = new Room(); $rt = $r[$i]; array_push($r2, $rt); } echo "\n ".$r[0]->x; //допустим 42 $r2[0]->x = 13; echo "\n ".$r[0]->x; //13! 

How to make so that to change a copy of objects and values ​​in the original did not change? Thanks for the help.

  • $ rt = clone $ r [$ i]; and remove the line $ rt = new Room (); - it is not used - Marsel Arduanov
  • You created the Room object in the $rt variable, and on the next line you are trying to put something in the $rt array under the $ i key, which is a bit strange) array_push($r2, clone($rt)); - jekaby
  • one of the solutions proposed at the moment does not work - WaldeMar
  • @WaldeMar do not believe! So something is not reflected in your example .. - jekaby

2 answers 2

Your example is a bit confusing. To work with a copy of an object, you need to create it using the clone keyword.

 class Room { public function __construct($value) { $this->x = $value; } public $x; } $r1 = new Room(10); $r2 = $r1; echo $r1->x . PHP_EOL; // 10 $r2->x = 20; echo $r1->x . PHP_EOL; // 20 

As you can see, by changing $ r2, the object $ r1 has changed, since objects in PHP by default are passed by reference.

Now compare with:

 $r1 = new Room(10); $r2 = clone($r1); echo $r1->x . PHP_EOL; // 10 $r2->x = 20; echo $r1->x . PHP_EOL; // 10 

    The problem was that each element of the $r array is a fairly large object, it has other objects, and arrays. In the end, I cloned (using the tips given to me here) so much of the internal object that I needed. Probably for cloning large objects you need to overload the __clone function inside the required classes. I have no idea how to do this.

    • hmm Well, yes, if there were links in the object, well, other objects (that is, in fact, if there were other objects in the object), then after cloning they remained references. And when modifying by reference, the original object also changes (after all, objects are passed by reference). Inside __clone , the idea is to redefine the necessary properties, i.e. apply clone() to internal objects: $ this-> obj = clone ($ this-> obj); - jekaby