PHP: How to pass instance variable to closure? PHP: How to pass instance variable to closure? php php

PHP: How to pass instance variable to closure?


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


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.


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();