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 “&”?
As @philip mentions, it is to return a reference:
From the above link:
PHP stores every variable in a ZVAL container.
From the above link:
Observe the values of variable in the output:
Consider the following without
&at the assignment of return value:The output for the above code:
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:The output: