PHP: How to pass instance variable to closure?

2019-06-20 09:14发布

问题:

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) { ...

回答1:

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


回答2:

You can use your workaround. You can also be more general:

$self = $this;
$func = function() use ($self) {
    echo "myVar = " . $self->myVar;
};

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.



回答3:

Why not ?:

    $func = function($param){ echo 'myVar is: ' . $param; };
    $func($this->myVar);

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:

    $this->myVar = 5;   
    $_var = $this->myVar;
    $func = function() use ($_var) { echo 'myVar is: ' . $_var; };
    $func();


标签: php closures