note 53895 added to language.references.arent
| From: | fzamperini_at_tin dot it at osu1 dot php dot net | Date: | Thu, 16 Jun 2005 09:35:18 +0000 |
| Subject: | note 53895 added to language.references.arent | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-90525@lists.php.net to get a copy of this message | ||
References are not like pointers.
If you try the example above in C/C++ you will find that after calling foo(var) you can get or set
the value of $GLOBALS["baz"] by reading or writing variable 'var' (I didn't
actually try it, but I vaguely remember it works this way).
In PHP this is also true if you do:
<?PHP
$var =& $GLOBALS["baz"];
?>
but *IT IS NOT* if you use a function to do that, in spite of
- using a reference as a parameter (function foo(&$var)) and
- assigning it a reference to the variable you want to bind ($var =& $GLOBALS["baz"])
inside the function
I tried this:
<?PHP
$GLOBALS["baz"] = 'globals_baz';
$bar = 'bar';
function foo (&$var)
{
$var =& $GLOBALS["baz"];
}
// Before 'binding' $bar to $GLOBALS["baz"] using a function
echo '$GLOBALS[baz]: ' . $GLOBALS["baz"] . "<BR>\n"; // Output
is 'globals_baz'
echo "\$bar: $bar <BR>\n"; // Output is 'bar'
foo($bar);
// After (what you may expected to be a) binding you should see that $bar is the same as
$GLOBALS[baz]:
echo "\$bar: $bar <BR>\n"; // it didn't work: output is still 'bar'
(not 'globals_baz')
// And setting $bar should set $GLOBALS[baz]:
$bar = 'bar';
echo '$GLOBALS[baz]: ' . $GLOBALS["baz"] . "<BR>\n"; // it
didn't work, too: output is still 'globals_baz' (not 'bar')
?>
If you change the calling of foo($bar) with $bar =& $GLOBALS["baz"]; it all works as
expected.
So the assertion, "references are not like pointers," might be a bit confusing but it is
fair.
----
Manual Page -- http://www.php.net/manual/en/language.references.arent.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+53895
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53895&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53895&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53895&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53895&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+53895&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53895&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+53895&report=yes
Search -- http://master.php.net/manage/user-notes.php