【问题标题】:php 5.3 access $this->method from Closurephp 5.3 从 Closure 访问 $this->method
【发布时间】:2013-08-19 09:19:28
【问题描述】:

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

【问题讨论】:

    标签: php closures


    【解决方案1】:

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

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

    【讨论】:

    • 它有效!但是私有方法呢? $object 无法访问它们
    • 你显然不能在 PHP5.3 的闭包中访问私有方法,因为它不是同一个“环境”。
    猜你喜欢
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2021-11-16
    • 2021-07-06
    • 2012-12-14
    相关资源
    最近更新 更多