This article provides a detailed analysis of php reference return and cancellation references. For more information, see
I. return a reference
The return value of the reference is used when you want to use the function to find the variable on which the reference should be bound. Do not use return references to increase performance. the engine is smart enough for optimization. A reference is returned only when there are reasonable technical reasons! To return a reference, use this syntax:
The code is as follows:
Class foo {
Public $ value = 42;
Public function & getValue (){
Return $ this-> value;
}
}
$ Obj = new foo;
$ MyValue = & $ obj-> getValue (); // $ myValue is a reference to $ obj-> value, which is 42.
$ Obj-> value = 2;
Echo $ myValue; // prints the new value of $ obj-> value, I. e. 2.
?>
The above is the explanation provided by PHP Manual and it is easy to understand.
The code is as follows:
Function & test (){
Static $ B = 0; // declare a static variable
$ B = $ B + 1;
Echo $ B ."
";
Return $ B;
}
$ A = test (); // The output value of $ B is: 1
$ A = 5;
$ A = test (); // The output value of $ B is: 2
$ A = & test (); // The output value of $ B is: 3 ** NOTE **
$ A = 5; // The value of $ B is changed to 5.
$ A = test (); // The output value of $ B is: 6 ** NOTE **
?>
$ A = test () although the return method is referenced when a function is defined, if a function is called in this normal situation, it serves the same purpose as a common function, so the result is 1 and 2.
$ A = & test () this call method is to reference and return, which is similar to $ a = & $ B. Then, in the second sentence, $ a = 5, that is, it equals to the variable $ B = 5, and the last sentence gets 6, which is easy to understand!
Unlike parameter transfer, the & symbol must be used here to indicate that a reference is returned instead of a normal copy. it also indicates that $ a is bound as a reference, instead of assigning values normally.
Note:If you try to return the reference from the function like this: return ($ this-> value);, this will not work because you are trying to return the result of an expression rather than a referenced variable. Only variables can be referenced from function return-no other method. If the code tries to return the result of a dynamic expression or new operator, an E_NOTICE error will be issued since PHP 4.4.0 and PHP 5.1.0.
II. cancel referencing
When unset is a reference, it only disconnects the binding between the variable name and the variable content. This does not mean that the variable content is destroyed. For example:
The code is as follows:
$ A = 1;
$ B = & $;
Unset ($ );
?>
Not unset $ B, just $.
It may be helpful to understand this analogy with the Unix unlink call.