Returning References from Functions

Returning a reference from a function allows you to directly operate on the return value and have those changes directly reflected in the original variable.

When returning a reference from a function, you must return a reference to a variable, not a string.

To return a reference from a function, you use the return statement, but you use & in front of its name when creating it. You also use & when getting the return value from a function that returns a reference.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
// Place an & before the name of the function
// if you want to return a value by reference.
function &Add(&$num1, $num2 = "3")
  {
  return $num1+$num2;
  }

// Set a value to a variable
$val = 2;

// You must use =& assignment operator to invoke the function.
// You pass the variable $val by reference for the first argument.
$sum =& Add($val);
echo "The sum is returned by reference: ", $sum, "<br />";
// Just take the value and not the reference
$sum = Add($val);
echo "The sum is returned by value: ", $sum, "<br />";

// The arguments are just passing by values
function &display_bold($string, $tag = 'b')
  {
  	return "<$tag>$string</$tag>";
  }
$string="Hello World";
$ref =& display_bold($string);
echo "The string is returned by reference: ", $ref, "<br />";
// Take the value
$ref = display_bold($string, 'i');
echo "The string is returned by value: ", $ref, "<br />";
?>
</p>
</body>
</html>

View the effect


Functions | What is a Function? | Defining a Function | Calling a Function | Passing Data | Variable Scope | Global Access | Setting Default Values for Arguments | Passing Arguments by Reference | Returning Values from Functions | Returning References from Functions | Static Variables | Creating Variable Functions | Creating Conditional Functions | Creating Functions within Functions | Include Files | Require Statement | Testing a Function | Type-Testing Functions | Handling Errors Returned by Functions
© 2008: Hann So
email: hso@voyager.deanza.edu