PHP - Passing References to Your Own Functions

Introduction

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

The function can alter the original value, rather than working on a copy.

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)
}

Now, whenever a variable is passed to myFunc(), PHP passes a reference to that variable, so that myFunc() can work directly with the original contents of the variable, rather than a copy.

Demo

<?php
function resetCounter( & $c) {
   $c = 0;/*from  ww  w.  ja  v  a 2s . c o m*/
}

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

Result

Adding the ampersand before the $c causes the $c parameter to be a reference to the passed argument ($counter).

Now, when the function sets $c to zero, it's actually setting the value of $counter to zero, as can be seen by the second echo statement.

PHP's sort() function changes the array you pass to it, sorting its elements in order.

The array is passed in by reference rather than by value, so that the function can change the array itself, rather than a copy of it.

Related Topic