Demystifying PHP

Variable by reference

Some people get confused about how to pass variables by reference.

Today I am going to show you and explain how this works.

First example:

$a = 5 ; // Variable = 5

$b = &$a; //& This symbol is called ampersand and in PHP it is used to pass a variable by reference.

echo $a; //The result will be 5;

echo $b; //The result will be 5;

Why?

A: $b received the value from $a through the '&' so now, $a is equal to 5 and $b as well.

Second example:

$a = 5; // Variable = 5

$b = &$a //& This symbol is called ampersand and in PHP it is used to pass a variable by reference.

$b = 20;

echo $a; //The result will be 20;

echo $b; //The result will be 20;

Why?

A: When the value of a variable is given to another variable that has no defined value, the given value prevails, but when the value is given to a variable that also has a defined value, the given value is ignored.

More details: When "b" received the value from "a" in the first example, b didn't have any value but in the second example the b value is 20. So the priority will be his own value. As a consequence b reflects its value for the variable a.

This article was written by
Marcos Barreiros