Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.




<?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
  
?>


Output:

2

Last Updated : 22 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads