Passing Values By Reference In PHP

16th February 2008

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.

  1. function wrap_html(&$string, $tag)
  2. {
  3. $string = ''.$string.''.$tag.'>';
  4. }
  5.  
  6. $line = 'This must be put in strong tags.';
  7. wrap_html($line, 'strong');
  8. echo $line; // prints out This must be put in strong tags.

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.

  1. function wrap_html(&$string, $tag)
  2. {
  3. $string = ''.$string.''.$tag.'>';
  4. }
  5.  
  6. define('LINE', 'This must be put in strong tags.');
  7. wrap_html(LINE, 'strong'); // script fatally dies here.
  8. echo $line;
  9. ?>

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.