Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么不是';这个引用调用的示例不起作用吗?_Php - Fatal编程技术网

Php 为什么不是';这个引用调用的示例不起作用吗?

Php 为什么不是';这个引用调用的示例不起作用吗?,php,Php,我正在澄清“通过引用调用”的概念。有人能解释下面显示的代码行作为“通过引用调用”的示例吗 <?php function test(){ $result = 10; return $result; } function reference_test(&$result){ return $result; } reference_test($result); ?> 您有两个问题 $res

我正在澄清“通过引用调用”的概念。有人能解释下面显示的代码行作为“通过引用调用”的示例吗

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

您有两个问题

  • $result
    从未设置,也从未调用测试函数
  • 您在错误的函数上执行了pass-by引用。传递引用用于更改函数内外的变量
  • 这是解决方案,稍微更改了函数以显示差异。您不需要返回通过引用更改的变量

    // 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
    

    请解释一下“不工作”是什么意思。你期望得到什么?您得到了什么结果?调用reference_test函数时,我想要值10,但它没有显示任何内容。