Reference variables PHP examples: &$var simple, pass by reference to function, array of reference variables

& preceeds variable

$original = “foo”;
$ref = &$original;
echo $ref; \\Prints “foo”
// now we change the value of $original
$original = “bar”;
// and then print the value of the referring variable
echo $ref; \\Now prints the new value: “bar”
source: http://www.whypad.com/posts/php-what-is-the-ampersand-preceding-variables/193/

reference variable (&variable)

<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

Basically, the argument is treated, referenced by the outside variable, as global
Without the &, it would output ‘This is a string’
source: http://php.net/manual/en/functions.arguments.php

 

An Array of Reference Variables:

// We have a bunch of variables
$var1 = 10;
$var2 = 100;
$var3 = 1000;
// Let’s put references to them all into an array. That way we can loop through them all, and edit one or all of them
$array = array(&$var1, &$var2, &$var3);
foreach($array as &$var){

if($var == 1000){

$var = 2000;

}

}
echo $var1 . “<br />”; // 10
echo $var2 . “<br />”; // 100
echo $var3 . “<br />”; // 2000

Comments are closed.