How To Return a Reference from a Function

Q

How To Return a Reference from a Function? - PHP Script Tips - Creating Your Own Functions

✍: FYIcenter.com

A

To return a reference from a function, you need to:

  • Add the reference operator "&" when defining the function.
  • Add the reference operator "&" when invoking the function.

Here is a PHP script on how to return a reference from a function:

<?php
$favor = "vbulletin";
function &getFavorRef() {
  global $favor;
  return $favor;
}
$myFavor = &getFavorRef();
print("Favorite tool: $myFavor\n");
$favor = "phpbb";
print("Favorite tool: $myFavor\n");
?>

This script will print:

Favorite tool: vbulletin
Favorite tool: phpbb

As you can see, changing the value in $favor does affect $myFavor, because $myFavor is a reference to $favor.

2007-04-14, 4786👍, 0💬