Monday, 11 November 2019

Creating closures with anonymous functions of PHP

Creating closures with anonymous functions

Megaphone
Another common use of anonymous functions is to create closures. A closure is a function that retains access to the variables in its enclosing scope, even if that scope has since disappeared.
For example:
  1. A function, myFunction(), contains a local variable (or parameter) called $myVar.
  2. The function also defines and returns an anonymous function that accesses $myVar.
  3. Some other code calls myFunction() and gets back the anonymous function, which it stores in $anonFunction. By this time, myFunction() has, of course, finished running.
  4. If the code now calls $anonFunction(), the anonymous function can still access the $myVar local variable that was in myFunction(), even though myFunction() is no longer running! The anonymous function, together with its reference to the $myVar variable, constitute a closure.
Rather confusingly, the PHP manual refers to anonymous functions as closures. They are not the same thing! Anonymous functions are used to create closures.
Closures can be difficult to get your head around at first, but once you grasp the concept, they let you write clean, powerful and flexible code. Let’s look at a couple of examples of closures to make things clearer.

No comments:

Post a Comment