In this tutorial we will explain how a PHP function can return by reference.
Return value of a Function
A function can return a value, such as 85, or a string literal. A function in addition can as well return a reference, i.e similair to &$ var. A function that returns a reference, it is as if you must put the function betweem & and $ var.
Function Returning a Reference
Study the code below:
<?php
function &func()
{
$ myVar = 85;
return $ myVar;
}
$ var = func();
echo $ var;
?>
You’ve got the definition of the function, func. In the function description, the name of the function starts with &. This implies the function will return a reference and not the value. In the function definition, you return the value ($ myVar above). Since the preceding & in the function name, the reference to the region in memory that retains the returned value is what is returned. This returned reference is allotted to an generic value in a function call statement.
In order to return a reference, introduce the function name in the function description with &. When the function returns a value, a reference to that value is returned. Study the following code whose function definition doesn’t contain a variable:
<?php
function &func()
{
return 85;
}
$ var = func();
echo $ var;
?>
In this instance, there isnt an original variable holding the value of interest (15). Nevertheless the reference to the value stacked away somewhere in a region in memory is returned.
Note: When calling the function that returns a reference, you do not precede the function call with &.
Affirming Returning by Reference
In the following code, you have 2 global variables. Additionally you have a function and a call to the function. The function changes the value of the 1st global variable. The function call returns the reference to the global variable, after it’s been altered inside the function. This returned reference is ascribed to the 2nd global variable. The 2 variables are then echoed displaying equal values, affirming that a reference has been returned. The returned reference is the reference to the value of the 1st global variable.
<?php
$ var1 = 85;
function &func()
{
global $ var1;
$ var1 = 37;
return $ var1;
}
$ var2 = func();
echo $ var1.”<br “;
echo $ var2.”<br “;
?>

