我不清楚以下方法是否有效:
class Sample {
private $value = 10;
public function something() {
return function() {
echo $this->value;
$this->someProtectedMethod();
}
}
protected function someProtectedMethod() {
echo 'hello world';
}
}
我使用的是 PHP 5.6,这将运行的环境是 5.6。我不确定两件事,这个范围。如果我可以在闭包函数中调用受保护的方法、私有方法和私有变量。
问题 #1 是一个简单的语法错误:
return function() {
echo $this->value;
$this->someProtectedMethod();
};
(注意分号(
现在,当您调用something()
时,此代码将返回实际函数....它不会执行该函数,因此您需要将该函数分配给变量。您必须显式调用该变量作为函数来执行它。
// Instantiate our Sample object
$x = new Sample();
// Call something() to return the closure, and assign that closure to $g
$g = $x->something();
// Execute $g
$g();
然后你进入作用域问题,因为调用$this
时$g
不在函数的作用域中。您需要将我们已经实例化的 Sample 对象绑定到闭包以提供$this
范围,因此我们实际上需要使用
// Instantiate our Sample object
$x = new Sample();
// Call something() to return the closure, and assign that closure to $g
$g = $x->something();
// Bind our instance $x to the closure $g, providing scope for $this inside the closure
$g = Closure::bind($g, $x)
// Execute $g
$g();
编辑
工作演示