php 5.3从Closure访问$ this->方法

时间:2013-08-19 09:19:29

标签: php closures

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

1 个答案:

答案 0 :(得分:3)

你需要使用“use”在闭包中添加对象,但是使用“别名”,因为$ this不能在闭包中注入。

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