Search code examples
phpcopy-on-writereference

sometimes we declare "&" ahead of function in class based coding


I am following class based coding for project development.I have recently seen that some times we put "&" ahead of function name..

for an example..

rather than defining

function test()

it is defined like

function &test()

is there any special meaning of "&"?


Solution

  • As @philip mentions, it is to return a reference:

    From the above link:

    Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.


    PHP stores every variable in a ZVAL container.

    From the above link:

    A zval container contains, besides the variable's type and value, two additional bits of information.The first is called "is_ref" and is a boolean value indicating whether or not the variable is part of a "reference set". With this bit, PHP's engine knows how to differentiate between normal variables and references. Since PHP allows user-land references, as created by the & operator, a zval container also has an internal reference counting mechanism to optimize memory usage. This second piece of additional information, called "refcount", contains how many variable names (also called symbols) point to this one zval container.


    Observe the values of variable in the output:
    Consider the following without & at the assignment of return value:

    $b=0;
    function &func ($name) {
      global $b;
      $b = 10;
      return $b;
      }
    $a = func("myname");// no & at assignment
    ++$a ;
    echo '<br/>$a= '.$a.' $b= ' .$b."<br/>";
    xdebug_debug_zval('a'); echo "<br/>";
    

    The output for the above code:

    $a= 11 $b= 10
    a: (refcount=1, is_ref=0)=11 
    

    Although the function returns by reference, the reference is for the returned value's zval container. Now, when we are trying to assign the returned value, (say without a & at the assignment) only the "refcount" will increase. Where as the "is_ref" will not be altered. When the 'variable in which the returned value is stored', is tried to alter, a C.O.W (copy on write) takes place and a new zval container is created rendering the return by reference useless. Hence you will need to add the & at the assignment of the return value as well.

    Consider the following with & at the assignment of return value:

    $b=0;
    function &func ($name) {
      global $b;
      $b = 10;
      return $b;
      }
    $a =& func("myname");// & at assignment
    ++$a ;
    echo '<br/>$a= '.$a.' $b= ' .$b."<br/>";
    xdebug_debug_zval('a'); echo "<br/>";
    

    The output:

    $a= 11 $b= 11
    a: (refcount=2, is_ref=1)=11