【问题标题】:Variable scope within functions and subfunctions? [duplicate]函数和子函数内的变量范围? [复制]
【发布时间】:2015-08-12 09:03:52
【问题描述】:

很抱歉,如果之前已经回答过这个问题 - 我搜索了但找不到明确的答案。

如果我有一个处理变量$x 的函数foo(),然后是一个子函数bar(),我如何访问$x

function foo(){       

    $x = 0;

    function bar(){

        //do something with $x

    }

}

这段代码是否正确,或者有更好的做法来访问父函数中的变量?

【问题讨论】:

    标签: php function scope


    【解决方案1】:

    在子函数中使用全局变量请注意:

    这将无法正常工作......

    <?php 
    function foo(){ 
        $f_a = 'a'; 
    
        function bar(){ 
            global $f_a; 
            echo '"f_a" in BAR is: ' . $f_a . '<br />';  // doesn't work, var is empty! 
        } 
    
        bar(); 
        echo '"f_a" in FOO is: ' . $f_a . '<br />'; 
    } 
    ?> 
    

    这会……

    <?php 
    function foo(){ 
        global $f_a;   // <- Notice to this 
        $f_a = 'a'; 
    
        function bar(){ 
            global $f_a; 
            echo '"f_a" in BAR is: ' . $f_a . '<br />';  // work!, var is 'a' 
        } 
    
        bar(); 
        echo '"f_a" in FOO is: ' . $f_a . '<br />'; 
    } 
    ?>
    

    更多信息请阅读这里http://php.net/manual/en/language.variables.scope.php php中的全局变量有缺点,所以请从这里阅读 Are global variables in PHP considered bad practice? If so, why?

    【讨论】:

    • 我知道使用global 是非常糟糕的做法。这是真的?并且在初始化变量访问它时是否需要声明global
    • 是的,两次。而且它不一定很糟糕,因为它容易出错。如果您使用 global,您将不知道哪个函数更改了哪个变量,因为可能有多个函数使用相同的全局变量。长话短说,它让调试变得非常困难。
    【解决方案2】:

    您可以像这样将其作为参数传递:

    function foo(){       
    
        $x = 0;
    
        function bar($x){
    
            //Do something with $x;
    
        }
    
        bar($x);
    
    }
    

    或者你可以创建一个闭包:

    function foo(){       
    
        $x = 0;
    
        $bar = function() use ($x) {
    
            //Do something with x
        };
    
        $bar();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2012-10-04
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多