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.