If you want to use a closure from within a class, how do you pass in an instance variable from that class?
class Example {
private $myVar;
public function test() {
$this->myVar = 5;
$func = function() use ($this->myVar) { echo 'myVar is: ' . $this->myVar; };
// The next line is for example purposes only if you want to run this code.
// $func is actually passed as a callback to a library, so I don't have
// control over the actual call.
$func();
}
}
$e = new Example();
$e->test();
PHP doesn't like this syntax:
PHP Fatal error: Cannot use $this as lexical variable in example.php on line 5
If you take off $this->
then it can't find the variable:
PHP Notice: Undefined variable: myVar in example.php on line 5
If you use use (xxx as $blah)
as suggested in some places, it seems invalid syntax whether you have $this
or not:
PHP Parse error: syntax error, unexpected 'as' (T_AS), expecting ',' or ')' in example.php on line 5
Is there a way to do this? The only way I can get it to work is with a dodgy workaround:
$x = $this->myVar;
... function() use ($x) { ...
If you are using PHP 5.4 or later, then you can use
$this
directly inside the closure:You can use your workaround. You can also be more general:
Within the closure you can access any public properties or methods using
$self
instead of$this
.But it won't work for the original question, because the variable in question is private.
Why not ?:
Update:
@Bramar right. But, if only $myVar will be
public
, it will work. Closures have no associated scope , so they cannot access private and protected members. In you specific case, you can do: