johanafm wrote:Anyway, would you care to explain, or tell me where to find this info.
The PHP manual's page on objects and references has the information that you seek.
johanafm wrote:The php.net page on return by reference seem to indicate otherwise to me.
On the contrary, it recommends quite clearly: "Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so."
In PHP 4, this was not true. A deep copy would otherwise be performed, so returning by reference was a valid optimisation technique.
johanafm wrote:Also, if you put things in the context of a class
Try this instead:
<?php
class a {
private $var;
public function a() {
$this->var = new b('original');
}
public function getVal() {
return $this->var;
}
public function &getRef() {
return $this->var;
}
}
class b {
private $x;
public function __construct($x) {
$this->x = $x;
}
public function transmogrify() {
$this->x = 'transmogrified';
}
public function __toString() {
return $this->x;
}
}
$a = new a();
$var = $a->getVal();
$ref = &$a->getRef();
$notRef = $a->getVal();
echo 'member: ' . $a->getVal() . PHP_EOL;
$var = new b('new');
echo PHP_EOL . 'assign to var: ' . $a->getVal() . PHP_EOL;
$notRef->transmogrify();
echo PHP_EOL . 'transmogrify notRef: ' . $a->getVal() . PHP_EOL;
$ref = new b('brand new');
echo PHP_EOL . 'assign to ref: ' . $a->getVal() . PHP_EOL;
EDIT:
Notice that I changed $notRef to hold the return value of $a->getVal(). So, we see that assigning new b('new') to $var caused the reference variable to hold a reference to a new object, thus there is no change to $a's b object. On the other hand, calling transmogrify() on $notRef caused $a's b object to change because $notRef holds a reference to the same object as the one contained in $a. But assigning to $ref caused $a's b object to change as well... except that it is a change of object, not just of the object's contents, since $ref is an alias for $a's b object.