Passing Values By Reference In PHP

For most functions it is normal for have the function return the output of a calculation. With PHP it is also possible to pass values to the function by reference. A better way of saying this is rather than pass the value of the variable you pass a pointer to the variable itself. When you do this anything that you do to the variable inside the function is also done outside, so if you interact with the variable again it will contain a different value.

The ampersand (&) character is used in the parameters of the function to stipulate that a parameter will be passed by reference.

Here is an example of this at work.

function wrap_html(&$string, $tag) {
  $string = '<'.$tag.'>'.$string.'</'.$tag.'>';
$line = 'This must be put in strong tags.';
wrap_html($line, 'strong');
echo $line; // prints out <strong>This must be put in strong tags.</strong>

The only limitation with this sort of functionality is that you can't pass a constant value. PHP will die with a fatal error if you try this. The following code will produce such an error.

function wrap_html(&$string, $tag) {
  $string = '<'.$tag.'>'.$string.'</'.$tag.'>';
define('LINE', 'This must be put in strong tags.');
wrap_html(LINE, 'strong');  // script fatally dies here.
echo $line;

The error produced is as follows.

Fatal error: Only variables can be passed by reference in test.php on line 7

To get around this issue you can dump the constant into a temporary variable and pass this variable to the function.

Add new comment

The content of this field is kept private and will not be shown publicly.
12 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.