PHP closure scope problem

后端 未结 3 931
野的像风
野的像风 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;
    }
    
    0 讨论(0)
  • 2020-12-30 10:28

    You can use the bindTo method.

    class MyClass {
      static function getHdvdsCol($pid) {
        $col = new PointColumn();
        $col->key = $pid;
        $parser = function($row) {
            print $this->key;
        };
        $col->parser = $parser->bindTo($parser, $parser);
        return $col;
      }
    }
    
    $func = MyClass::getHdvdsCol(45);
    call_user_func($func, $row);
    
    0 讨论(0)
  • 2020-12-30 10:50

    You need to specify which variables should be closed in this way:

    function($row) use ($pid) { ... }
    
    0 讨论(0)
提交回复
热议问题