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. To return by reference is handy for using a function to detect a variable a reference to be bound to.

It is not recommended to use return-by-reference for increasing performance.

Watch a course Learn object oriented PHP

An Example of Using Ampersand

For a better perception, let’s consider a detailed example of using an ampersand to start a PHP function.

Instead of a copy, it is necessary to set the property of the object that is returned by getValue().

In contrast to passing a parameter, here, you should put the ampersand in both of the places for specifying that you want to return by reference.

The example will look as follows:


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;


References and Ampersands in PHP

Two variables can be referred to the same content with the help of references.

Otherwise saying, a variable specifies its content instead of becoming that content.

Passing by reference gives an opportunity to two variables to specify the same content under distinct names. To be referenced an ampersand should be put before the variable.