note 22981 deleted from language.variables by nlopess
| From: | nlopess@php.net | Date: | Fri, 24 Dec 2004 20:32:54 +0000 |
| Subject: | note 22981 deleted from language.variables by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-82272@lists.php.net to get a copy of this message | ||
Note Submitter: stlawson AT sbcglobal DOT net
----
In 'ghent's comment on the 'above example' I think he confuses the confusion ;)
Here is the example referred to:
<?php
$foo = 'Bob'; // Assign the value 'Bob' to $foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $bar;
echo $foo; // $foo is altered too.
?>
Reference $foo via $bar/Alter $bar
IS correct, but it is a little obscure. Heres what
it means:
$bar is assigned a reference to $foo, thus $bar references or points to $foo which contains the
string Bob. Essentially what is happening here is Bob is stored in memory at a particular
address. &$foo returns that address [where Bob is stored]. That address is assigned to
$bar. So, in the string My name is $bar, $bar uses the address it contains to find Bob
(which is in $foo) and thus the string becomes My name is Bob. When the string is assigned
to $bar, because $bar refers to $foo, it gets assigned to the same address location that Bob is
stored at, thus Bob is overwritten by My name is Bob. The trick here is to realize that
$bar behaves as if it is $foo, so when something is assigned to $bar (the alias of $foo), its as
if it was being assigned to $foo!
After the above script is run, the output will look like this:
My name is BobMy name is Bob
e.g. both $foo and $bar print the same thing.
In C++ the same code snippit would look like this:
foo = Bob ;
bar = &foo ;
bar = My name is + *bar ;
Notice that in C/C++ it is necessary to manually dereference the pointer (*bar) PHP does this
automagically.
BTW: You might think that echo $bar; would display the address of $foo not so! More PHP
automagic ;)