Anonymous functions do not use lexical scope, but $this is a special case and will be automatically available inside the function from 5.4.0 . Your code should work as expected, but it will not be portable for older versions of PHP.
Below will be no :
protected function _pre() { $methodScopeVariable = 'whatever'; $this->require = new Access_Factory(function($url) { echo $methodScopeVariable; }); }
Instead, if you want to embed variables in the closing area, 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 access $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.
source share