Dec
11
PHP - Variable References
December 11, 2007 |
In PHP, references are how you create variable aliases. To make $Seinfeld an alias for the variable $funny_guy, use:
$Seinfeld =& $funny_guy;
Let’s take a look at the example below to get a bettering unsderstanding of variable references:
$reference = "Rock"; $aliase =& $reference; $reference .= " rocks!"; print "\$aliase is $aliase<br />"; print "\$reference is $reference<br />"; $aliase = "Actor $aliase"; print "\$aliase is $aliase<br />"; print "\$reference is $reference";
By executing the code above, you will get the output like something below:
$aliase is Rock rocks!
$reference is Rock rocks!
$aliase is Actor Rock rocks!
$reference is Actor Rock rocks!
From the result, we can see two points: 1. If we update value of $reference, the value $aliase will be the same as the lasted updated $reference value. 2. If we update the value of $aliase, the value of $reference will also be updated.
Functions can return values by reference (for example, to avoid copying large strings or arrays). For example:
function &ret_ref() {
$var = "PHP";
echo $var;
return $var;
}
$v =& ret_ref( );
Note you need to use the & before the function name ret_ref().
Similar Posts
- None Found
Comments
1 Comment so far



































[...] Check it out! While looking through the blogosphere we stumbled on an interesting post today.Here’s a quick excerptIf we update value of $reference, the value $aliase will be the same as the lasted updated $reference value. 2. If we update the value of $aliase, the value of $reference will also be updated. Functions can return values by reference … [...]