问题
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