PHP - Returning References from Your Own Functions

Introduction

You can get functions to return references, rather than values.

To do this, you place an ampersand before the function name in your function definition.

Then, when you return a variable with the return statement, you pass a reference to that variable back to the calling code, rather than the variable's value:

function  & myFunc(){
   // (do stuff)
   return $var;  // Returns a reference to $var
}

Here's an example that shows return-by-reference in action:

Demo

<?php

$myNumber = 5;/*from   w ww  . j a va  2s .c  o  m*/

function  & getMyNumber() {
    global $myNumber;
    return $myNumber;
}

$numberRef = &  getMyNumber();
$numberRef++;
echo"\$myNumber = $myNumber \n";   // Displays"6"
echo"\$numberRef = $numberRef \n"; // Displays"6"
?>

Result

First, a global variable, $myNumber, is created and given the value 5.

Next, a function, getMyNumber(), is defined.

This function uses the global keyword to access the global variable $myNumber, then returns $myNumber.

Because getMyNumber() has an ampersand before its name, it returns a reference to $myNumber, rather than the value that $myNumber holds.

Next, the script calls getMyNumber().

The return value of getMyNumber() - that is, the reference to $myNumber - is then assigned to a new variable, $numberRef.

Related Topic