0

如何使用 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();
4

1 回答 1

3

You need to add object in the closure with "use", but using an "alias" because $this cannot be injected in a closure.

$object = $this;
$this->test(function($key, $value)use($object){
    $object->echoKey($key, $value); // not working on php 5.3
});
于 2013-08-19T09:22:56.210 回答