Passing References to Your Own Functions php

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.
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 actually passes a reference to that variable, so
that myFunc() can work directly with the original contents of the variable, rather than a copy.
Now that you know this, you can fix the earlier counter example by using a reference:
function resetCounter( & $c ) {
$c = 0;
}
$counter = 0;
$counter++;
$counter++;
$counter++;
echo “$counter < br/ > ”; // Displays “3”
resetCounter( $counter );
echo “$counter < br/ > ”; // Displays “0”
The only change in the script is in the first line:
function resetCounter( & $c ) {
Adding the ampersand before the $c causes the $c parameter to be a reference to the passed argument
( $counter in this example). 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.
Many built - in PHP functions accept references in this way. For example, PHP ’ s sort() function, which you
met in the previous chapter, 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.