What does it mean to start a PHP function with an ampersand?

An ampersand just before the function name will return a reference to the variable instead of returning its value. Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. In PHP 4, objects were assigned by value, just like any other value. This is highly counter-intuitive and opposite to how most other languages work.

Example: This example demonstrate the concept behind putting an ampersand to start a PHP function.

The property of the object returned by the getValue() function would be set instead of the copy as it would be without using reference syntax. Unlike parameter passing, here you have to use the ampersand in both the places to indicate that you want to return by reference rather than a copy and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
class student
{
    public $value = 42;
  
    public function &getValue()
    {
        return $this->value;
    }
}
  
$obj = new student;
  
// $myValue is a reference to 
// $obj->value, which is 42.
$myValue = & $obj->getValue(); 
$obj->value = 2;
  
// Prints the new value of 
// $obj->value, i.e. 2.
echo $myValue
  
?>

chevron_right


Output:

2
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.