note 92348 added to language.references.pass
| From: | Tom at osu1 dot php dot net | Date: | Mon, 20 Jul 2009 23:54:06 +0000 |
| Subject: | note 92348 added to language.references.pass | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158525@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 69.147.83.197
Probable Submitter: 92.227.76.193
----
Manual Page -- http://www.php.net/manual/en/language.references.pass.php
Edit -- https://master.php.net/note/edit/92348
Del: integrated -- https://master.php.net/note/delete/92348/integrated
Del: useless -- https://master.php.net/note/delete/92348/useless
Del: bad code -- https://master.php.net/note/delete/92348/bad+code
Del: spam -- https://master.php.net/note/delete/92348/spam
Del: non-english -- https://master.php.net/note/delete/92348/non-english
Del: in docs -- https://master.php.net/note/delete/92348/in+docs
Del: other reasons-- https://master.php.net/note/delete/92348
Reject -- https://master.php.net/note/reject/92348
Search -- https://master.php.net/manage/user-notes.php