Ok, I got totally lost on that one. Could you rephrase that, for my poor PHP4 entrenched mind and provide a PHP5 example to contrast with?
Well, let's start with an example in PHP 4. Suppose we have:
<?php
class X {
var $x;
function X($x) {
$this->x = $x;
}
function get() {
return $this;
}
}
$a = new X(1);
echo $a->x . ' ';
$b = $a->get();
echo $b->x . ' ';
$b->x = 2;
echo $a->x . ' ' . $b->x;
?>
We will find that '1 1 1 2' is printed. The reason is that $b->x = 2 only sets the $x member in $b, not $a. But if we switch to PHP 5 and run the same code, we will get '1 1 2 2'. The reason is that $a->get() returns a reference to the $this object, i.e., $b now points to the same object as $a.
However, the unfortunate part is that this is like Java's reference mechanism, not C++, whereas the usual PHP pass by reference mechanism is like C++, not Java. In PHP 5 $a->get() returns a reference that acts like a pointer (but without pointer syntax). So if we were to change $b instead of changing $b->x:
$b = new X(2);
... we will find that the output is back to '1 1 1 2'. The reason is that $b = new X(2) makes $b point to the new X object, without making $a do the same. $a still points to the first X object with the $x member having a value of 1.
If we use the PHP 4 version:
<?php
class X {
var $x;
function X($x) {
$this->x = $x;
}
function& get() {
return $this;
}
}
$a = new X(1);
echo $a->x . ' ';
$b =& $a->get();
echo $b->x . ' ';
$b = new X(2);
echo $a->x . ' ' . $b->x;
?>
Now we find that even with the use of $b = new X(2), $a->x is now 2, not 1 (i.e., we get '1 1 2 2' as the output). The reason is that $b =& $a->get() makes $b into an alias (i.e., in C++ reference style) of $a. So changing $b itself changes $a.