PHP & ampersand: Passing by reference

In PHP, variable name and variable content are different. The same content can have more than one names, each name references the same content which means each reference has access to the same variable content. If you change the variable content using one variable name, it will effect every other variable name that is referencing the same variable content. It is like filenames and files in linux, variable names like the filepath and variable content is the like the file itself, and the file can be hardlinked in many different directories. Changes to one hardlinked file, it will effects all the hardlinked files the same way because they are referencing the same file content.

So, how do we create more than one variable names to reference the same variable content in php? The answer is create a new varialbe by passing the reference. To do so, put an ampersand & before the variable name and assign to to a new varialbe name.

Pass by reference example of a single variable.

$origin = 1;
$ref = &$origin; // Create a new variable name to reference the same variable content as $origin, currently 1
$ref = $ref + 1; // 1 is added to $ref, which effects $origin the same way
echo "ref is equal to $ref, and origin is equal to $origin which is the same as the ref<br/>";

Pass by reference example of an array.

$originArray = array(0,1,2,3,4,6,7,8,9);
foreach ($originArray as &$value){
$value = $value + 1;
//Break the binding between the variable name and variable content. 
//A good practice to do so when the referece is no longer needed.
unset ($value);

echo "<br/>";

Pass by reference example of passing the value as a reference to a function.

function addOne(&$var){ 
$origin = 1;
echo "origin is $origin, which was incremented by 1 in function addOne<br/>";

Search within Codexpedia

Custom Search

Search the entire web

Custom Search