The php reference returns a detailed explanation of the dereference

  • 2020-06-12 08:37:38
  • OfStack

1. Reference return
Reference return is used when you want to use a function to find which variable the reference should be bound to. Instead of using return references to increase performance, the engine is smart enough to optimize itself. Only return references if there are valid technical reasons! To return a reference, use this syntax:


<?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.
?>

That's PHP Manual's explanation and it's too easy to understand

<?php
    function &test(){
     static $b = 0;  // The statement 1 Static variables 
     $b = $b+1;
     echo $b."<br>";
     return $b;
    }
   $a = test();  // The output  $b  The value is: 1
   $a = 5;
   $a = test();  // The output  $b  The value is: 2

   $a = &test();  // The output  $b  The value is: 3  ** Pay attention to **
   $a = 5;    //$b Theta is going to be theta 5
   $a = test();  // The output  $b  The value is: 6  ** Pay attention to **
   ?>

$a = test() although the function is defined as a reference return, if the function is called in this normal situation, it will behave just like the normal function 1, so the result is 1, 2

$a = & test() is a call that returns a reference, similar to $a = & $b, then $a = 5 in the second sentence, that is equal to the variable $b = 5, the last sentence gets 6 is easy to understand!
Unlike parameter passing, this has to be used in both places & Symbol - indicates that 1 reference is returned instead of the usual 1 copy, and also indicates that $a is used as a binding for the reference, not the usual assignment.

Note: If you try to return a reference from a function like this: return ($this-) > value); This will not work because you are trying to return the result of an expression instead of a referenced variable. You can only return a reference variable from a function -- nothing else. If the code attempts to return the result of a dynamic expression or the new operator, an E_NOTICE error will be issued from PHP 4.4.0 and PHP 5.1.0.

2. Unquote
When unset 1 reference, it simply breaks the binding between the variable name and the variable content. This does not mean that the variable content is destroyed. Such as:

<?php
$a = 1;
$b =& $a;
unset($a);
?>

Not unset $b, just $a.
It may be useful to compare this to the unlink call of Unix 1.


Related articles: