Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to pass instance variable to closure?

Tags:

closures

php

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) { ...
like image 336
Malvineous Avatar asked May 23 '14 01:05

Malvineous


1 Answers

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;
};
like image 68
Felix Kling Avatar answered Oct 06 '22 04:10

Felix Kling