Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP have lexical scope in anonymous functions / closures?

I'm using PHP 5.4 and wondering if the anonymous functions I'm making have lexical scoping?

I.e. If I have a controller method:

protected function _pre() {
    $this->require = new Access_Factory(function($url) {
        $this->redirect($url);
    });
}

When the Access Factory calls the function it was passed, will the $this refer to the Controller where it was defined?

like image 388
Charles Avatar asked May 03 '13 17:05

Charles


1 Answers

Anonymous functions don't use lexical scoping, but $this is a special case and will automatically be available inside the function as of 5.4.0. Your code should work as expected, but it will not be portable to older PHP versions.


The following will not work:

protected function _pre() {
    $methodScopeVariable = 'whatever';
    $this->require = new Access_Factory(function($url) {
        echo $methodScopeVariable;
    });
}

Instead, if you want to inject variables into the closure's scope, you can use the use keyword. The following will work:

protected function _pre() {
    $methodScopeVariable = 'whatever';
    $this->require = new Access_Factory(function($url) use ($methodScopeVariable) {
        echo $methodScopeVariable;
    });
}

In 5.3.x, you can get access to $this with the following workaround:

protected function _pre() {
    $controller = $this;
    $this->require = new Access_Factory(function($url) use ($controller) {
        $controller->redirect($url);
    });
}

See this question and its answers for more details.

like image 89
Matt Kantor Avatar answered Oct 18 '22 20:10

Matt Kantor