Home  >  Article  >  Backend Development  >  Questions about php references

Questions about php references

WBOY
WBOYOriginal
2016-08-31 08:54:511050browse

//Return by reference

<code>function &testReturn(){  
    static $b = 1;  
    $b += 2;  
    return $b;  
}  
$a = &testReturn();  
$a = 8;  
$c = &testReturn();
$c = 12;
$d = testReturn();  
//echo $d;  

function &cuitReturn(){
    $a = 2;
    return $a;
}
$cr = &cuitReturn();
//echo $cr;
$cr = 4;
$cr1 = cuitReturn();
echo $cr1;
</code>

The second function changes the value of the assigned variable, $cr = 4; why does the return value of the function not change?

Reply content:

//Return by reference

<code>function &testReturn(){  
    static $b = 1;  
    $b += 2;  
    return $b;  
}  
$a = &testReturn();  
$a = 8;  
$c = &testReturn();
$c = 12;
$d = testReturn();  
//echo $d;  

function &cuitReturn(){
    $a = 2;
    return $a;
}
$cr = &cuitReturn();
//echo $cr;
$cr = 4;
$cr1 = cuitReturn();
echo $cr1;
</code>

The second function changes the value of the assigned variable, $cr = 4; why does the return value of the function not change?

The code of your first function is actually like this, because $b is a static variable, so it will not be released after the function is executed.

<code class="php">...    //省略代码
$c = &$b;
$c = 12;    //此处$b为12
$d = testReturn();    //$b+2
echo $d; //当然是14而不是7</code>

But in the second function $a is a local variable. After the function is executed, the memory of this variable is released.

First of all, we need to make it clear whether the calling function returns a reference. The function name must be preceded by &, and the assignment statement must be preceded by &. So, in the title of the question, $cr1 = cuitReturn();is actually not a reference.

Back to what the questioner said, why the return value has not changed? It’s because the $a in the function cuitReturn is a local variable, and it is not static, so it is released after the function returns, $cr = &cuitReturn();It is equivalent to referencing a local variable, If this is placed in C++, it will cause big trouble...This means that the pointer points to unknown memory,But the PHP engine should handle it, so$rc The reference to $a is invalid

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn