How to Start a PHP Function with an Ampersand
In PHP, an ampersand is put before the function name for returning a reference to the variable instead of returning the value. Learn how to do that, here.
In PHP, an ampersand (<kbd class="highlighted">&</kbd>) is placed before the function name to return a reference to a variable instead of its value. Returning by reference is useful when you need a function to bind directly to a specific variable.
It is not recommended to use return-by-reference for performance optimization. In PHP 7+, copy-on-write semantics handle value copying efficiently, making this practice unnecessary.
An Example of Returning a Reference
To illustrate, let’s consider a detailed example of using an ampersand to return a reference from a PHP function.
This allows you to modify the original object property directly, rather than working with a copy.
Unlike passing parameters by reference, returning by reference requires the ampersand in both the function definition and the assignment statement.
The example will look as follows:
php use ampersand to return by reference
<?php
class pupil
{
public $value = 42;
public function &getValue()
{
return $this->value;
}
}
$obj = new pupil();
// $myValue is a reference to
// $obj->value, which is 42.
$myValue = &$obj->getValue();
$obj->value = 2;
// Printing the new value of
// $obj->value, i.e. 2.
echo $myValue;
?>php use ampersand to return by reference, output
2References and Ampersands in PHP
References allow two variables to point to the same content.
In other words, a variable holds a reference to its content rather than being the content itself.
Passing by reference allows two variables to share the same content under different names. To create a reference, place an ampersand before the variable name.