note 76272 added to language.oop5.basic
| From: | Stephen at osu1 dot php dot net | Date: | Sun, 08 Jul 2007 23:54:04 +0000 |
| Subject: | note 76272 added to language.oop5.basic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-128310@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 69.147.83.197
Probable Submitter: 68.163.193.97
----
Manual Page -- http://www.php.net/manual/en/language.oop5.basic.php
Edit -- https://master.php.net/note/edit/76272
Del: integrated -- https://master.php.net/note/delete/76272/integrated
Del: useless -- https://master.php.net/note/delete/76272/useless
Del: bad code -- https://master.php.net/note/delete/76272/bad+code
Del: spam -- https://master.php.net/note/delete/76272/spam
Del: non-english -- https://master.php.net/note/delete/76272/non-english
Del: in docs -- https://master.php.net/note/delete/76272/in+docs
Del: other reasons-- https://master.php.net/note/delete/76272
Reject -- https://master.php.net/note/reject/76272
Search -- https://master.php.net/manage/user-notes.php