note 43278 added to language.oop.newref

From: Date: Wed, 16 Jun 2004 16:02:55 +0000
Subject: note 43278 added to language.oop.newref
Groups: php.notes 
Request: Send a blank email to php-notes+get-71149@lists.php.net to get a copy of this message
As a bit of a newbie to objects, I found the final example very hard to work out at first. I'd like to try and explain more clearly: It all centres around what the $this variable actually is. The answer is, it's an object. It's the object that the $this variable is currently inside. So let's say we call the first instance of class A that is created by my script "Instance1". If I say, <?php class A { function test() { $foo = $this; } } $myclass = new A(); ?> ... then $this is the object Instance1. Note that it is *NOT* the same as the object $myclass, as $myclass is simply a *COPY* of the object Instance1. This means that if you create an object using the copy (=) operator, there is an instance of the object (in this case, Instance1) hanging around unreferenced. Whereas if we use the reference (=&) operator to create an object, the first instance (Instance1) is directly referenced by the variable specified, and no copy is created. eg. <?php class A { function test() { $foo = $this; } } $myclass =& new A(); ?> ... this assigns the variable $myclass directly to Instance1, with no need for Instance1 to be copied. There is only one instance of the class created, and it is assigned to $myclass. In brief, if we use <--> to indicate a reference between a variable and an instance of a class: Statement | Results in... $myclass = new A(); | Instance1 Instance2<-->$myclass (Instance2 is a copy) $myclass =& new A(); | Instance1<-->$myclass All seems simple when you see the diagram, eh? :-) Of course, you may be asking the question, "Why doesn't the '=' operator just make $myclass reference first object Instance1? Why would you ever need Instance1 to be copied, surely all you'd ever want or need is a direct reference to the newly created object Instance1?" Well, that's the same question I and others are asking. Hopefully this behaviour will change in a later version of PHP. Hope that helps. ---- Manual Page -- http://www.php.net/manual/en/language.oop.newref.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+43278 Delete -- http://master.php.net/manage/user-notes.php?action=delete+43278&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+43278&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#71149) next »