Access a global variable in a PHP function

前端 未结 9 1982
感动是毒
感动是毒 2020-11-29 05:33

According to the most programming languages scope rules, I can access variables that are defined outside of functions inside them, but why doesn\'t this code work?



        
9条回答
  •  [愿得一人]
    2020-11-29 06:14

    PHP can be frustrating for this reason. The answers above using global did not work for me, and it took me awhile to figure out the proper use of use.

    This is correct:

    $functionName = function($stuff) use ($globalVar) {
     //do stuff
    }
    $output = $functionName($stuff);
    $otherOutput = $functionName($otherStuff);
    

    This is incorrect:

    function functionName($stuff) use ($globalVar) {
     //do stuff
    }
    $output = functionName($stuff);
    $otherOutput = functionName($otherStuff);
    

    Using your specific example:

        $data = 'My data';
    
        $menugen = function() use ($data) {
            echo "[" . $data . "]";
        }
    
        $menugen();
    

提交回复
热议问题