note 41323 added to language.oop

From: Date: Tue, 06 Apr 2004 14:33:10 +0000
Subject: note 41323 added to language.oop
Groups: php.notes 
Request: Send a blank email to php-notes+get-67711@lists.php.net to get a copy of this message
In these notes almost everybody sais to do the following when creating new objects: $obj=&new Object(); good, or almost good.. Now consider this: // Class definition class a{ var $obj; function a($counter){ $this->obj =& new b($counter); } } class b{ var $id; function b($counter){ $this->id=$counter; } function setId($newId){ $this->id=$newId; } } // definitions end $a1=&new a(1); $a2=&new a(2); $a3=$a2; print_r($a3); $a3->obj->setId("123"); print "a1<br><hr>"; print_r($a1); print "<hr>"; print "a2<br><hr>"; print_r($a2); print "<hr>"; print "a3<br><hr>"; print_r($a3); print "<hr>"; With this code, you died... In fact since you copied the object $a2 into another a object named $a3 and you think you have a brand new object, well you dont. Since we are using a reference to a constructor inside a constructor (in the a object constructor we use =&new b()) this object is common to $a2 AND it's COPY ($a3). Indeed, if you change the value of $a3->obj->id you will also change it for the copy. That's what you wanted ? Fine for you. But I needed a real copy so I was force to use "=" and not "=&" in the constructor of the a object. Maby this is making object referencing a little clearer for some of you.. Good Luck! ---- Manual Page -- http://www.php.net/manual/en/language.oop.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+41323 Delete -- http://master.php.net/manage/user-notes.php?action=delete+41323&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+41323&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#67711) next »