简体   繁体   中英

php 5.3 access $this->method from Closure

How to access method from closure with PHP 5.3? The code below could run on PHP 5.4 without a problem:

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();

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM