One, reference return
Reference return is used when you want to use a function to find the reference to which variable it should be bound. Do not use return references to increase performance, the engine is smart enough to optimize itself. Return the reference only if there is a reasonable technical reason! To return a reference, use this syntax:
Copy Code code as follows:
<?php
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 given by PHP manual and it is too good to understand
Copy Code code as follows:
<?php
function &test () {
static $b = 0; Declaring a static variable
$b = $b +1;
echo $b. " <br> ";
return $b;
}
$a = Test (); The output $b value is: 1
$a = 5;
$a = Test (); The output $b value is: 2
$a = &test (); The output $b value is: 3 * * NOTE * *
$a = 5; $b value changed to 5.
$a = Test (); The output $b value is: 6 * * NOTE * *
?>
$a = Test ()Although the function definition is referred to as the return method, but if the normal situation to invoke the function, it is the same as ordinary functions, so see the result is 1, 2
$a = &test ()This invocation is a reference return, similar to the $a = & $b, and then the second sentence $a = 5, which is equal to the variable $b = 5, the last sentence to get 6 is easy to understand!
Unlike parameter passing, there must be a & symbol in two places--indicating that the return is a reference rather than a common copy, and also that $a is a reference binding rather than a normal assignment.
Note:If you try to return a reference from a function like this: Returns ($this->value), this will not work because you are trying to return the result of an expression rather than a referenced variable. You can only return reference variables from a function--no other way. If the code attempts to return the result of a dynamic expression or the new operator, a e_notice error is emitted from PHP 4.4.0 and PHP 5.1.0.
Ii. Cancellation of references
When unset a reference, only the binding between the variable name and the variable content is disconnected. This does not mean that the variable content has been destroyed. For example:
Copy Code code as follows:
<?php
$a = 1;
$b =& $a;
unset ($a);
?>
Not unset $b, just $a.
Taking this analogy with Unix's unlink may help to understand.