Skip to content

Instantly share code, notes, and snippets.

@msankhala
Last active June 13, 2022 14:15
Show Gist options
  • Save msankhala/3a51b8dcc480e656a682 to your computer and use it in GitHub Desktop.
Save msankhala/3a51b8dcc480e656a682 to your computer and use it in GitHub Desktop.
Understanding Ampersand Before PHP Function Names – Returning By Reference
<?php
// You may have wondered how a PHP function defined as below behaves:
function &config_byref()
{
static $var = "hello";
return $var;
}
// the value we get is "hello"
$byref_initial = config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We still get "hello"
// However, let’s make a small change:
// We’ve added an ampersand to the function call as well. In this case, the function returns "world", which is the new value.
// the value we get is "hello"
$byref_initial = &config_byref();
// let's change the value
$byref_initial = "world";
// Let's get the value again and see
echo "Byref, new value: " . config_byref() . "\n"; // We now get "world"
// If you define the function without the ampersand, like follows:
// function config_byref()
// {
// static $var = "hello";
// return $var;
// }
// Then both the test cases that we had previously would return "hello", regardless of whether you put ampersand in the function call or not.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment