PHP closure scope problem

后端 未结 3 944
野的像风
野的像风 2020-12-30 10:22

Apparently $pid is out of scope here. Shouldn\'t it be \"closed\" in with the function? I\'m fairly sure that is how closures work in javascript for example.

Accordi

3条回答
  •  鱼传尺愫
    2020-12-30 10:24

    I think PHP is very consistent in scoping of variables. The rule is, if a variable is defined outside a function, you must specify it explicitly. For lexical scope 'use' is used, for globals 'global' is used.

    For example, you can't also use a global variable directly:

    $n = 5;
    
    function f()
    {
        echo $n; // Undefined variable
    }
    

    You must use the global keyword:

    $n = 5;
    
    function f()
    {
        global $n;
        echo $n;
    }
    

提交回复
热议问题