note 22981 added to language.variables

From: Date: Fri, 05 Jul 2002 22:47:18 +0000
Subject: note 22981 added to language.variables
Groups: php.notes 
Request: Send a blank email to php-notes+get-32650@lists.php.net to get a copy of this message
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. Here’s 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), it’s 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 ;) -- http://www.php.net/manual/en/language.variables.php http://master.php.net/manage/user-notes.php?action=edit+22981 http://master.php.net/manage/user-notes.php?action=delete+22981 http://master.php.net/manage/user-notes.php?action=reject+22981

« previous php.notes (#32650) next »