Does PHP have a lexical scope in anonymous functions / closures?

I am using PHP 5.4 and wondering if anonymous functions have a lexical definition?

those. If I have a controller method:

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

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

+6
source share
2 answers

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.

+6
source

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

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

edit: since Matt rightly pointed out support for $this in closure running with PHP 5.4

+1
source

Source: https://habr.com/ru/post/944239/


All Articles