php 5.3访问$this->;方法


php 5.3 access $this->method from Closure

如何使用PHP 5.3从闭包访问方法?下面的代码可以在PHP 5.4上运行而不会出现问题:

class ClassName
{
  function test(Closure $func)
  {
    $arr = array('name' => 'tim');
    foreach ($arr as $key => $value) {
      $func($key, $value);
    }
  }
  function testClosure()
  {
    $this->test(function($key, $value){
    //Fatal error: Using $this when not in object context
    $this->echoKey($key, $value); // not working on php 5.3
  });
}
function echoKey($key, $v)
{
  echo $key.' '.$v.'<br/>'; 
}
}
$cls = new ClassName();
$cls->testClosure();

您需要在闭包中添加带有"use"的对象,但要使用"alias",因为$this不能注入到闭包中。

$object = $this;
$this->test(function($key, $value)use($object){
    $object->echoKey($key, $value); // not working on php 5.3
});