note 82791 added to language.references

From: Date: Fri, 25 Apr 2008 18:35:08 +0000
Subject: note 82791 added to language.references
Groups: php.notes 
Request: Send a blank email to php-notes+get-138780@lists.php.net to get a copy of this message
It took me a long while until I fully understood the sentence mentioned above: "They (references) are not like C pointers; instead, they are symbol table aliases." Here is a little example to that. <?php class AnyClass { public $member; public function __construct($val) { $this->member = $val; } } $manyObjects = array(); $obj = null; for($i = 0; $i < 5;$i++) { $obj = new AnyClass($i); // create new instance $manyObjects[] = &$obj; // i did not wanted to copy, just store the reference in the array, which turned out to be WRONG (it is not reference to the CLASS INSTANCE what is stored in the array, but rather reference to what variable with NAME $obj CURRENTLY holds). // so we end up as shown below } for($i = 0; $i < 5;$i++) { echo "Value:".$manyObjects[$i]->member."\r\n"; } /** * Output is : * Value:4 * Value:4 * Value:4 * Value:4 * Value:4 * instead of expected * Value:0 * Value:1 * Value:2 * Value:3 * Value:4 */ // If we change the value of $obj later in the script, all members would be changed in that moment $obj = 1; print_r($manyObjects); /* Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 1 ) */ ?> Hope this spares someone few hours of time ;-) ---- Server IP: 147.32.160.17 Probable Submitter: 83.208.63.167 ---- Manual Page -- http://www.php.net/manual/en/language.references.php Edit -- https://master.php.net/note/edit/82791 Del: integrated -- https://master.php.net/note/delete/82791/integrated Del: useless -- https://master.php.net/note/delete/82791/useless Del: bad code -- https://master.php.net/note/delete/82791/bad+code Del: spam -- https://master.php.net/note/delete/82791/spam Del: non-english -- https://master.php.net/note/delete/82791/non-english Del: in docs -- https://master.php.net/note/delete/82791/in+docs Del: other reasons-- https://master.php.net/note/delete/82791 Reject -- https://master.php.net/note/reject/82791 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#138780) next »