Closures in PHP

Some explanation of closures in the PHP with examples

Serhii Shkarupa
2 min readSep 15, 2022

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.

Closure class has own methods and parameters

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.

Variable $count keep alive and change state after method count() line 16 has ended his work

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

Not sure how principles of encapsulation feels here

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.

Example of usage

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:

Example with inbuilt functions

I hope you were able to find something interesting for yourself in this article.

--

--