Saturday, 4 June 2016

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

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...