PHP Return Reference

In this chapter you will learn:

  1. How to return a reference
  2. Syntax to return reference from a function
  3. 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:

  1. What is the scope of a variable
  2. Example - variable scope
Home » PHP Tutorial » PHP Function Create
PHP Function
PHP Function Create
PHP Function Parameter
PHP Function Default Parameters
PHP Variable Length Parameter
PHP Function Reference Parameter
PHP Function Return
PHP Return Reference
PHP Variable Scope in Functions
PHP Global Variables
PHP Recursive Functions
PHP Anonymous Function
PHP static variable