note 92348 deleted from language.references.pass by googleguy

From: Date: Sun, 23 Feb 2014 17:18:24 +0000
Subject: note 92348 deleted from language.references.pass by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-198604@lists.php.net to get a copy of this message
Note Submitter: Tom ---- Still puzzled with references? See this code: <?php function a(&$a, &$b) { $a =& $b; } $a = 1; $b = 2; a($a, $b); $b = 3; print $a; ?> If you expect the output to be 3, you are wrong. $a remains unchanged and the output is 1. The reference was NOT assigned to $a. Now let's try this one: <?php function a(&$a, &$b) { $a = $b; } $a = 1; $b = 2; a($a, $b); $b = 3; print $a; ?> If you thought that now the output would be 3, you are wrong again. It's 2. However this: <?php $a = 1; $b = 2; $a =& $b; $b = 3; print $a; ?> Actually outputs 3. But how about Objects? Objects, you might think, are always passed by reference. So this should work! Well, let's check it out: <?php function a($a, $b) { $a = $b; } $a = new StdClass; $a->i = 1; $b = new StdClass; $b->i = 2; a($a, $b); $b->i = 3; print $a->i; ?> Outputs 1! So obviously you are wrong again. What's the reason? Simple! The first (and the last) code example above translates to this fragment: <?php $a = 1; $b = 2; $a1 =& $a; $b1 =& $b; $a1 =& $b1; $b = 3; print $a; ?> Now THAT makes it clear, right? If you are referencing a reference you are NOT making the original pointer change it's destination like in Java or C#, because it is not dereferenced automatically. Instead you are overwriting the local pointer. You will make $a1 point to $b, which has no influence on the original $a. This is different from all you might expect if you have been programming in other OO-languages before, so you should keep that in mind.

« previous php.notes (#198604) next »