Reference returns
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;
The second function, changing the value of the assignment variable, $CR = 4; Why did the return value of the function not change?
Reply content:
Reference returns
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;
The second function, changing the value of the assignment variable, $CR = 4; Why did the return value of the function not change?
Your first function, the code is actually like this, because $b it is a static variable, so the function will not be released after execution.
... //省略代码$c = &$b;$c = 12; //此处$b为12$d = testReturn(); //$b+2echo $d; //当然是14而不是7
But the second function $a is a local variable, the function is finished, the memory of this variable is freed.
The first thing to be clear is whether the calling function returns a reference function name preceded by a &, and the assignment statement is preceded by A & so the title $cr1 = cuitReturn(); is actually not a reference to this point.
Back to the main said, why the return value is not changed, because cuitReturn the function $a is a local variable, and is not static, so the function is returned after the release, equivalent to a $cr = &cuitReturn(); reference to a local variable, which if placed in C + + will be a big event ... This means that the pointer is pointing to an unknown memory, but the PHP engine should be handled, so $rc the reference to it $a is invalid