PHP Function 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  w  w  w. ja  v  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/*from w w  w .j a v a  2 s . com*/
    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.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition