How to use $this inside php closure? [duplicate]

喜夏-厌秋 提交于 2019-12-12 10:22:58

问题


I have code like this:

class Foo {
   var $callbacks = array();
   function __construct() {
      $this->callbacks[] = function($arg) {
         return $this->bar($arg);
      };
   }
   function bar($arg) {
      return $arg * $arg;
   }
}

and I would like to use $this inside closures, I've try to add use ($this) but this throw error:

Cannot use $this as lexical variable

回答1:


You cannot use $this as this is an explicit reserved variable for the class inside reference to the class instance itself. Make a copy to $this and then pass it to the use language construct.

class Foo {
   var $callbacks = array();
   function __construct() {
      $class = $this;
      $this->callbacks[] = function($arg) use ($class) {
         return $class->bar($arg);
      };
   }
   function bar($arg) {
      return $arg * $arg;
   }
}



回答2:


Give $this to another var and use that.

class Foo
{
    public function bar()
    {
        $another = $this;
        return function() use($another)
        {
            print_r($another);
        };
    }
}


来源:https://stackoverflow.com/questions/39182290/how-to-use-this-inside-php-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!