函数和子函数中的变量作用域


Variable scope within functions and subfunctions?

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

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

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

这个代码是正确的,还是有更好的实践访问父函数中的变量?

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

这将无法正常工作…

<?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中有缺点,所以请从这里阅读全局变量在PHP中被认为是不好的做法吗?如果是,为什么?

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

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();
}