Returning a Reference from a Function in PHP

Q

How To Return a Reference from a Function? in PHP?

✍: 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.

 

Specifying Argument Default Values in PHP

Function Returns Data by Value in PHP

Creating Your Own Functions in PHP

⇑⇑ PHP Tutorials

2016-12-08, 2108🔥, 0💬