Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php 5.3 access$this->;闭包法_Php_Closures - Fatal编程技术网

php 5.3 access$this->;闭包法

php 5.3 access$this->;闭包法,php,closures,Php,Closures,如何使用PHP5.3从闭包访问方法?下面的代码可以在PHP 5.4上运行,不会出现问题: class ClassName { function test(Closure $func) { $arr = array('name' => 'tim'); foreach ($arr as $key => $value) { $func($key, $value); } } function testClosure() {

如何使用PHP5.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();
类名
{
功能测试(闭包$func)
{
$arr=array('name'=>'tim');
foreach($arr作为$key=>$value){
$func($key,$value);
}
}
函数testClosure()
{
$this->test(函数($key,$value){
//致命错误:不在对象上下文中使用$this
$this->echoKey($key,$value);//不适用于PHP5.3
});
}
功能echoKey($key,$v)
{
回显$key.'.$v.
; } } $cls=新类名(); $cls->testClosure();
您需要在闭包中添加带有“use”的对象,但要使用“alias”,因为$this不能注入闭包中

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

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

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

它起作用了!但是私有方法呢$对象不能访问它们在PHP5.3中,显然不能访问闭包中的私有方法,因为它不是同一个“环境”。它可以工作!但是私有方法呢$对象无法访问它们在PHP5.3中,您显然无法访问闭包中的私有方法,因为它与“环境”不同。