jcubic jcubic - 3 months ago 20
PHP Question

How to use $this inside php closure?

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

Answer

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