<?php
function f(& $var){$var = rand(); return $var;}
echo f($var ="a_").'<br/>'; /* outpu a random number */
echo $var.'<br/>'; /*but don't change global variables, it still is "1<br/>", no the same like up line */
echo f($var).'<br/>'; /* outpu a random number */
echo $var.'<br/>'; /* haved change, the same like up line */
?>
run up code and output text like under block
28486
a_
25863
25863
Wwhy can’t change the $var in the first call?
<?php
function f(& $var, & $isRefer){$var = rand(); global $gVar; var_dump(array('are they same?' => $isRefer === $gVar)); return $var;}
$gVar = 'global var';
echo f($var ="a_", $gVar = & $gVar).'<br/>'; /* outpu a random number */
echo $var.'<br/>'; /*but don't change global variables, it still is "1<br/>", no the same like up line */
echo f($var, $gVar).'<br/>'; /* outpu a random number */
echo $var.'<br/>'; /* haved change, the same like up line */
?>
-the code output like-
array(1) {
[“are they same?”]=>
bool(true)
}
14802
a_
array(1) {
[“are they same?”]=>
bool(true)
}
19107
19107
so i think it is pass value like f($var = 'd') by “refer”
Passing variables by reference is a special case of function calling. Typically only the value of an expression is passed into the function as parameter.
Here
3 * 4is an expression that evaluates to12, so12is passed into the function. A function that expects variables to be passed by reference though is different, because it needs a variable:The purpose of passing by reference is to be able to modify the passed variable, not just a value. As such, you need to actually pass it a variable, not just a value. Calling the function with something like
f(3 * 7)doesn’t make much sense in this case. Well,f($var = 'foo')is the same thing.$var = 'foo'is an expression, it’s not simply a variable. Therefore only the result of the expression (the value) is passed, not any variable that happens to appear in the expression.To illustrate that better, which variable should be passed when doing
f($foo + $bar)? The answer is that it just doesn’t work that way. To pass a variable by reference, you can only use a variable as the parameter, not an expression.