PHP:如何传递实例变量到闭包? [英] PHP: How to pass instance variable to closure?
本文介绍了PHP:如何传递实例变量到闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果要在类中使用闭包,那么如何从该类传递一个实例变量?
If you want to use a closure from within a class, how do you pass in an instance variable from that class?
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 doesn't like this syntax:
PHP Fatal error: Cannot use $this as lexical variable in example.php on line 5
如果你取消 $ this->
,那么它找不到变量:
If you take off $this->
then it can't find the variable:
PHP Notice: Undefined variable: myVar in example.php on line 5
b $ b
如果你在某些地方使用使用(xxx as $ blah)
,这似乎无效语法是否有 $ this
或不:
If you use use (xxx as $blah)
as suggested in some places, it seems invalid syntax whether you have $this
or not:
PHP Parse error: syntax error, unexpected 'as' (T_AS), expecting ',' or ')' in example.php on line 5
?我可以让它工作的唯一方法是使用一个解决方法:
Is there a way to do this? The only way I can get it to work is with a dodgy workaround:
$x = $this->myVar;
... function() use ($x) { ...
推荐答案
如果您使用PHP 5.4或更高版本,那么您可以直接在闭包中使用 $ this
:
If you are using PHP 5.4 or later, then you can use $this
directly inside the closure:
$func = function() {
echo 'myVar is: ' . $this->myVar;
};
这篇关于PHP:如何传递实例变量到闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文