如果要在类中使用闭包,如何从该类传递实例变量?
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();
Run Code Online (Sandbox Code Playgroud)
PHP不喜欢这种语法:
PHP Fatal error: Cannot use $this as lexical variable in example.php on line 5
Run Code Online (Sandbox Code Playgroud)
如果你起飞$this->那么它找不到变量:
PHP Notice: Undefined variable: myVar in example.php on line 5
Run Code Online (Sandbox Code Playgroud)
如果你use (xxx as $blah)按照某些地方的建议使用,无论你有$this没有,它似乎都是无效的语法:
PHP Parse error: syntax error, unexpected 'as' (T_AS), expecting ',' or ')' in example.php on line 5
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?我可以让它工作的唯一方法是使用一个狡猾的解决方法:
$x = $this->myVar;
... function() use ($x) { ...
Run Code Online (Sandbox Code Playgroud)
如果您使用的是PHP 5.4或更高版本,那么您可以$this直接在闭包内使用:
$func = function() {
echo 'myVar is: ' . $this->myVar;
};
Run Code Online (Sandbox Code Playgroud)
您可以使用您的解决方法.你也可以更一般:
$self = $this;
$func = function() use ($self) {
echo "myVar = " . $self->myVar;
};
Run Code Online (Sandbox Code Playgroud)
在闭包中,您可以使用$self而不是使用任何公共属性或方法$this.
但它不适用于原始问题,因为有问题的变量是私有的.
| 归档时间: |
|
| 查看次数: |
2643 次 |
| 最近记录: |