如果要在类中使用闭包,如何从该类中传递实例变量?
class Example {
private $myVar;
public function test() {
$this->myVar = 5;
$func = function() use ($this->myVar) { echo 'myVar is: ' . $this->myVar; };
// The next line is for example purposes only if you want to run this code.
// $func is actually passed as a callback to a library, so I don't have
// control over the actual call.
$func();
}
}
$e = new Example();
$e->test();
PHP不喜欢此语法:
PHP Fatal error: Cannot use $this as lexical variable in example.php on line 5
如果起飞,$this->
则找不到变量:
PHP Notice: Undefined variable: myVar in example.php on line 5
如果您use (xxx as $blah)
在某些地方按照建议使用,则无论是否使用,语法似乎都是无效的$this
:
PHP Parse error: syntax error, unexpected 'as' (T_AS), expecting ',' or ')' in example.php on line 5
有没有办法做到这一点?我可以使其正常工作的唯一方法是使用狡猾的解决方法:
$x = $this->myVar;
... function() use ($x) { ...
如果您使用的是PHP 5.4或更高版本,则可以$this
在闭包内部直接使用:
$func = function() {
echo 'myVar is: ' . $this->myVar;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句