Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

In short, no, but you can access public methods & functions by passing it:

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

edit: as Matt rightly pointed out support for $this in closures started with PHP 5.4

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top