What does & before the function name signify?

Viewed 9768

What does the & before the function name signify?

Does that mean that the $result is returned by reference rather than by value? If yes then is it correct? As I remember you cannot return a reference to a local variable as it vanishes once the function exits.

function &query($sql) {
 // ...
 $result = mysql_query($sql);
 return $result;
}

Also where does such a syntax get used in practice ?

4 Answers
  <?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.
Related