【发布时间】:2013-12-26 10:28:12
【问题描述】:
有没有办法将$this 绑定到作为参数传递的闭包?
我阅读并重新阅读了我可以在手册或互联网上找到的所有内容,但没有人提到这种行为,除了这篇博文:
http://www.christophh.net/2011/10/26/closure-object-binding-in-php-54/
其中提到了它,但没有说明如何做。
所以这里有一个例子。当调用get(function() {}) 方法时,我希望传递给它的回调函数绑定到对象,即绑定到$this,但不幸的是它不起作用。有什么办法可以吗?
class APP
{
public $var = 25;
public function __construct() {
}
public function get($callback) {
if (!is_callable($callback)) {
throw new InvalidArgumentException('Paran must be callable.');
}
// $callback->bindTo($this);
$callback->bindTo($this, $this);
$callback();
}
}
$app = new APP();
$app->get(function() use ($app) {
echo '<pre>';
var_dump($app);
echo '<br />';
var_dump($this);
});
$app 有效。 $this 为 NULL。
【问题讨论】: