What is a reference assignment in PHP?

A reference assignment in PHP in respect of variables is when a variable references another variable.

So for example 2 variables…

$a = 'red';

$b = 'blue';

echo $a . '<br>';

echo $b . '<br>';

The first echo output will produce ‘red’ and ‘blue’

Now change $b to reference $a

$b =& $a;

echo $a . '<br>';

echo $b . '<br>';

The second will output ‘red’ and ‘red’.

The use of the ampersand in the 2nd assignment of $b means that the value of $b now is the value of $a.

Remove the reference assignment

To remove the reference assignment you can use the unset() function, so in the example above to remove $b

unset($b);

echo $a . '<br>'; 

echo $b . '<br>';

Now the output will just be the value of ‘red’ as the $b value no longer exists. If you have error warnings enabled you will see an undefined notice for the $b variable.

Using a reference in a functions argument

You can use a reference to a variable as an argument to a function, consider a more numeric style function

function color_counter($var) {

    $var = $var + 10;

}

$red_ball = 5;

color_counter($red_ball);

echo $red_ball;

The value will still be 5 as $red_ball is a global variable – now pass the argument as a reference…

function color_counter(&$var) {

    $var = $var + 10;

}

$red_ball = 5;

color_counter($red_ball);

echo $red_ball;

Now the value will be 15 as the argument has a preceding ampersand indicating it is a reference to whatever is brought into the argument which in this case is $red_ball which has a global value of 5 – then after the addition is 15.

 

Using a reference in a functions return value

You can also use a reference in a functions return value

function &color_return() {
	global $a;
	$a = $a * 2;
	return $a;
}

$a = 15;
$b =&color_return();

So in the above the ampersand is used in the function name and when assigning the variable as a reference to the function the ampersand is also used.
The output of $a and $b would both be 15.

If you assigned later in the code $b to another value

$b = 'potato head';
echo "{$a}{$b}"; 

Then echoed out a and b they would both be potato head as $b is now referenced as the return value.

Using a reference in a instance of a class

In terms of OOP PHP you can make a reference of an instance of a class by using the word  $this

class MyExample {
	
	function method_inside_example() {
		echo 'Method from inside example I am called ' . get_class($this) . '
';
	}

	function hello() {
		$this->method_inside_example();
	}
}


$blackboard = new MyExample();
$blackboard->method_inside_example();
$blackboard->hello();

So an instance is made of the class $blackboard -then it calls 2 methods, the first one outputs the class name in the method_inside_example method and the second one hello calls the method_inside_example method, both examples use the $this reference.

Leave all Comment