note 76272 deleted from language.oop5.basic by felipe
| From: | felipe@php.net | Date: | Mon, 24 Mar 2008 22:13:11 +0000 |
| Subject: | note 76272 deleted from language.oop5.basic by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137475@lists.php.net to get a copy of this message | ||
Note Submitter: Stephen
----
jcastromail at yahoo dot es stated:
****
in php 5.2.0 for classes
$obj1 = $obj2;
is equal to
$obj1 = &$obj2;"
****
However, that is not completely true. While both = and =& will make a variable refer to the same
object as the variable being assigned to it, the explicit reference assignment (=&) will keep
the two variables joined to each other, whereas the assignment reference (=) will make the assigned
variable an independent pointer to the object. An example should make this clearer:
<?php
class z {
public $var = '';
}
$a = new z();
$b =& $a;
$c = $a;
$a->var = null;
var_dump($a);
print '<br>';
var_dump($b);
print '<br>';
var_dump($c);
print '<br><br>';
$a = 2;
var_dump($a);
print '<br>';
var_dump($b);
print '<br>';
var_dump($c);
print '<br><br>';
?>
This outputs:
object(z)#1 (1) { ["var"]=> NULL }
object(z)#1 (1) { ["var"]=> NULL }
object(z)#1 (1) { ["var"]=> NULL }
int(2)
int(2)
object(z)#1 (1) { ["var"]=> NULL }
So although all 3 variables reflect changes in the object, if you reassign one of the variables that
were previously joined by reference to a different value, BOTH of those variables will adopt the new
value.
Perhaps this is because =& statements join the 2 variable names in the symbol table, whereas =
statements applied to objects simply create a new independent entry in the symbol table that simply
points to the same location as other entries. I don't know for sure - I don't think this
behavior is documented in the PHP manual, so perhaps somebody with more knowledge of PHP's
internals can clarify what is going on.