|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2018-12-03 16:12 UTC] cmb@php.net
-Status: Open
+Status: Not a bug
-Package: PHP Language Specification
+Package: Scripting Engine problem
[2018-12-03 16:12 UTC] cmb@php.net
[2018-12-03 16:12 UTC] cmb@php.net
-Assigned To:
+Assigned To: cmb
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 02 08:00:02 2025 UTC |
Description: ------------ I have a method (addFinal) in a class that copy an object from an array and put it into another, I use clone to avoid the possibility to modify the original object. The modification "ONLY_MODIFY_THIS" affects several objects, when is supposed to affect only the first. I want two things: 1. Preserve original objects D1, D2 and D3 2. Modify only the object indexed in the finals array. Test script: --------------- class I { public $name; public $value; public function __construct( $name, $value ) { $this->name = $name; $this->value = $value; } } class D { public $name; public $items; public function __construct( $name ) { $this->name = $name; $this->items = array( 'I1' => new I( "I1", 1232 ), 'I2' => new I( "I2", 12 ), 'I3' => new I( "I3", "hello" ) ); } public function addItem( Item $item ) { array_push( $this->items, $item ); } } class B { public $values; public function __construct() { $this->values = array( "D1" => new D("D1"), "D2" => new D("D2"), "D3" => new D("D3")); } } class A { public $name; public $bobject; public $finals; public function __construct() { $this->bobject = new B(); $this->finals = array(); } public function addFinal( $name ) { $final = clone $this->bobject->values[$name]; array_push( $this->finals, $final ); } } class C extends A { } $c = new C(); $c->addFinal( "D1" ); $c->addFinal( "D1" ); $c->addFinal( "D1" ); $c->addFinal( "D1" ); $c->addFinal( "D2" ); $c->addFinal( "D3" ); $c->addFinal( "D1" ); $c->finals[0]->name = "HelloWorld"; $c->finals[0]->items["I1"]->name="ONLY_MODIFY_THIS"; print_r( $c ); exit; Expected result: ---------------- 1. Preserve original objects D1, D2 and D3 2. Modify only the object indexed in the finals array. Actual result: -------------- The code is modifying multiple variable prevously cloned from an original object. I believe something is wrong there.