PHP Function Reference Parameter

In this chapter you will learn:

  1. What is a reference
  2. Syntax to create reference variable
  3. Reference variable
  4. Syntax for reference parameters
  5. Function Reference Parameters
  6. Example - Reference parameter

Description

A reference is a pointer to a PHP variable.

Syntax to create reference variable

$myRef = &$myVariable;

Reference variable

We have two ways to read or change the variable's contents. We can use the variable name, or you can use the reference.

Here's a simple example that creates a reference to a variable:


<?PHP//from  j  av a  2 s. c  om
         $myVar = 123; 
         $myRef = &$myVar; 
         $myRef++; 
         echo $myRef . "\n";  // Displays "124" 
         echo $myVar . "\n";  // Displays "124"   
?>

The code above generates the following result.

First a new variable, $myVar, is initialized with the value 123. Next, a reference to $myVar is created, and the reference is stored in the variable $myRef.

Note the ampersand (&) symbol after the equals sign; using this symbol creates the reference.

Because $myRef actually points to the same data. The next line of code adds one to the value of as $myVar, both $myRef and $myVar now contain the value 124.

Syntax for reference parameters

To get a function to accept an argument as a reference rather than a value, put an ampersand (&) before the parameter name within the function definition:


function myFunc(  & $aReference ){ 
  // (do stuff with $aReference) 
}   

Note

By passing a reference to a variable as an argument to a function, rather than the variable itself, you pass the argument by reference , rather than by value.

This means that the function can now alter the original value, rather than working on a copy.

Example 1

Reference parameter


<?PHP//  j a  v a2s . c om
    function resetCounter(  & $c ) { 
      $c = 0; 
    } 

    $counter = 0; 
    $counter++; 
    $counter++; 
    $counter++; 
    echo "$counter\n";  // Displays "3" 
    resetCounter( $counter ); 
    echo "$counter\n";  // Displays "0"   
?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is function return
  2. Note for function return
  3. Example - return value from a function
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