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:
$func = function() {
echo 'myVar is: ' . $this->myVar;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With