note 41323 deleted from language.oop by aidan
| From: | aidan@php.net | Date: | Sat, 03 Jul 2004 14:46:32 +0000 |
| Subject: | note 41323 deleted from language.oop by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72432@lists.php.net to get a copy of this message | ||
Note Submitter: sleblanc@radicalhorizon.com
----
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!