2016-02-03 88 views
0

它不清楚,我如果下面将工作:闭包在一个类和受保护的方法

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

问题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被调用。您需要绑定,我们已经实例化以封闭为$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(); 

编辑

Working Demo