PHP Using Closures in arrays

Have you ever thought some day how to iterate a list of functions in php. In this tutorial i will show a feature in PHP 5.4 and above related to Closures  and arrays which is how to create arrays that contain a Closures. With This feature in place you can iterate an array of functions and execute them one by one.


Let’s demonstrate this with examples

Now let’s say i want to iterate over all these functions with another function that accepts a variable number of arguments:

This works pretty well:

Remember to use this feature in a class you have to define the array in the constructor:

Or (slightly better in terms of readable code) define the functions in the class and reference them from the array

If you don’t want to write out all the methods by hand in the $fns array you could use this dirty trick to get all function names in the class without the ‘magic’ methods like __construct and __autoload:


Share this: