PHP Return Reference
In this chapter you will learn:
- How to return a reference
- Syntax to return reference from a function
- Example - Return reference from a function
Description
As well as passing variables by reference into functions, you can also get functions to return references, rather than values.
Syntax
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
}
Example
Return reference from a function
<?PHP//from java 2s. c o m
$myNumber = 5;
function &getMyNumber() {
global $myNumber;
return $myNumber;
}
$numberRef = &getMyNumber();
$numberRef++;
echo "\$myNumber = $myNumber\n"; // Displays "6"
echo "\$numberRef = $numberRef\n"; // Displays "6"
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » PHP Tutorial » PHP Function Create