Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 22 May, 2020
Geek Week

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.

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :