Closures in PHP
Some explanation of closures in the PHP with examples
What is it?
Closure is the class, which represents anonymous functions. This means that you can store the function to any variable and this variable will be the object of the Closure class.
Also!
If parent function returns a closure as a result of work, variables of parent function will be available in the child function, despite the parent function has finished her work. Thus, the nested function closure the parent scope on itself, preventing them from being destroyed.
New this
If you check the Closure class methods, you can find that we are able to assign new object for our closure. See example below
How can be used?
In case you want to add ability for extending functionality. Some before- or -after cases. As for example you want to notify client after purchase. You create a list of all callbacks, which will notify clients with own logic. For adding new logic all what do you need is create new callback and add it to the list.
We can pass both regular functions as well as objects using magic method __invoke.
Also you can find a lot of callable parameters for PHP inbuilt functions, as for example array_map:
I hope you were able to find something interesting for yourself in this article.