note 43278 deleted from language.oop.newref by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Nov 2009 19:11:12 +0000 |
| Subject: | note 43278 deleted from language.oop.newref by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162586@lists.php.net to get a copy of this message | ||
Note Submitter: php dot net at game-point dot net
----
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.