PHP closure scope problem

非 Y 不嫁゛ 提交于 2019-12-03 19:13: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.

According to some articles php closures are broken, so I cannot access this?

So how can $pid be accessed from this closure function?

class MyClass {
  static function getHdvdsCol($pid) {
    $col = new PointColumn();
    $col->key = $pid;
    $col->parser = function($row) {
        print $pid; // Undefined variable: pid
    };
    return $col;
  }
}

$func = MyClass::getHdvdsCol(45);
call_user_func($func, $row);

Edit I have gotten around it with use: $col->parser = function($row) use($pid). However I feel this is ugly.


回答1:


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

function($row) use ($pid) { ... }



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/6543419/php-closure-scope-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!