PHP - Function References

Introduction

PHP passes copies of the information to and from the function; this is known as passing and returning by value.

Sometimes you may want your function to work on the original information, rather than on a copy.

You can use PHP references to work with the reference of variable.

A reference is like an alias to the variable.

When you create a reference to a PHP variable, you have two ways to read or change the variable's contents:

  • you can use the
  • variable name, or
  • you can use the reference.

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

Demo

<?php

$myVar = 123;//from w w  w. j  av  a2 s. co  m
$myRef = &$myVar;
$myRef++;
echo $myRef."\n";  // Displays"124"
echo $myVar."\n";  // Displays"124"
?>

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.

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

The next line of code adds one to the value of $myRef.

Because $myRef actually points to the same data as $myVar, both $myRef and $myVar now contain the value 124.

Related Topics