如何在PHP闭包中使用$ this? [英] How to use $this inside php closure?
本文介绍了如何在PHP闭包中使用$ this?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的代码:
class Foo {
var $callbacks = array();
function __construct() {
$this->callbacks[] = function($arg) {
return $this->bar($arg);
};
}
function bar($arg) {
return $arg * $arg;
}
}
,我想在闭包中使用$ this,我尝试添加 use($ this)
,但是抛出错误:
and I would like to use $this inside closures, I've try to add use ($this)
but this throw error:
Cannot use $this as lexical variable
推荐答案
您不能使用 $ this
,因为这是对类实例本身的引用内的类的显式保留变量。复制到 $ this
,然后将其传递给 use
语言构造。
You cannot use $this
as this is an explicit reserved variable for the class inside reference to the class instance itself. Make a copy to $this
and then pass it to the use
language construct.
class Foo {
var $callbacks = array();
function __construct() {
$class = $this;
$this->callbacks[] = function($arg) use ($class) {
return $class->bar($arg);
};
}
function bar($arg) {
return $arg * $arg;
}
}
这篇关于如何在PHP闭包中使用$ this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文