Creating closures with anonymous functions
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:
- A function,
myFunction()
, contains a local variable (or parameter) called$myVar
. - The function also defines and returns an anonymous function that accesses
$myVar
. - 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. - If the code now calls
$anonFunction()
, the anonymous function can still access the$myVar
local variable that was inmyFunction()
, even thoughmyFunction()
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