为什么这个引用调用的例子不起作用?


Why isn't this example of call by reference not working?

我正在清除按引用调用的概念。谁能解释一下下面的代码行作为引用调用的例子?

 <?php
    function test(){
        $result = 10;
        return $result;
    }
    function reference_test(&$result){
        return $result;
    }
    reference_test($result);
 ?>

你有两个问题

  1. $result不设置,测试函数不调用。
  2. 在错误的函数上执行引用传递。引用传递是改变函数内部和外部的变量。

这是解决方案,稍微改变了函数来显示不同之处。您不需要返回通过引用更改的变量。

// Pass by ref: because you want the value of $result to change in your normal code.
// $nochange is pass by value so it will only change inside the function.
function test(&$result, $nochange){ 
    $result = 10;
    $nochange = 10;
}
// Just returns result
function reference_test($result){ 
    return $result;
}
$result = 0; // Set value to 0
$nochange = 0;
test($result, $nochange); // $result will be 10 because you pass it by reference in this function
// $nochange wont have changed because you pass it by value.
echo reference_test($result); // echo's 10
echo reference_test($nochange); // echo's 0