note 102123 added to language.references.whatdo

From: Date: Fri, 28 Jan 2011 06:38:44 +0000
Subject: note 102123 added to language.references.whatdo
Groups: php.notes 
Request: Send a blank email to php-notes+get-176406@lists.php.net to get a copy of this message
It appears that references can have side-effects. Below are two examples. Both are simply copying one array to another. In the second example, a reference is made to a value in the first array before the copy. In the first example the value at index 0 points to two separate memory locations. In the second example, the value at index 0 points to the same memory location. I won't say this is a bug, because I don't know what the designed behavior of PHP is, but I don't think ANY developers would expect this behavior, so look out. An example of where this could cause problems is if you do an array copy in a script and expect on type of behavior, but then later add a reference to a value in the array earlier in the script, and then find that the array copy behavior has unexpectedly changed. <?php // Example one $arr1 = array(1); echo "\nbefore:\n"; echo "\$arr1[0] == {$arr1[0]}\n"; $arr2 = $arr1; $arr2[0]++; echo "\nafter:\n"; echo "\$arr1[0] == {$arr1[0]}\n"; echo "\$arr2[0] == {$arr2[0]}\n"; // Example two $arr3 = array(1); $a =& $arr3[0]; echo "\nbefore:\n"; echo "\$a == $a\n"; echo "\$arr3[0] == {$arr3[0]}\n"; $arr4 = $arr3; $arr4[0]++; echo "\nafter:\n"; echo "\$a == $a\n"; echo "\$arr3[0] == {$arr3[0]}\n"; echo "\$arr4[0] == {$arr4[0]}\n"; ?> ---- Server IP: 69.147.83.197 Probable Submitter: 74.217.68.123 ---- Manual Page -- http://www.php.net/manual/en/language.references.whatdo.php Edit -- https://master.php.net/note/edit/102123 Del: integrated -- https://master.php.net/note/delete/102123/integrated Del: useless -- https://master.php.net/note/delete/102123/useless Del: bad code -- https://master.php.net/note/delete/102123/bad+code Del: spam -- https://master.php.net/note/delete/102123/spam Del: non-english -- https://master.php.net/note/delete/102123/non-english Del: in docs -- https://master.php.net/note/delete/102123/in+docs Del: other reasons-- https://master.php.net/note/delete/102123 Reject -- https://master.php.net/note/reject/102123 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#176406) next »