..


Sponsored Links

Closures and Anonymous functions in PHP 5.3

Article written by Riccardo Brambilla
Page 1 of 2

As of PHP 5.3 are available Anonymous functions (lambda functions) and Closures ... but what is it?

Anonymous functions

The anonymous function (or lambda) are functions (without names) that have as their main use (though not only) to be defined as callback functions.

For those of you asking what is a callback function could simplify the definition in this way: a function passed as argument to another function.

Perhaps it is better to see an example, for clarity let's see first written in pseudocode, the callbacks are not anonymous and in fact the prerogative of PHP:






 / / Callback #







 callback function (parameter)

 





 DO something with the parameter







 return result processing









 / / # Caller







 calling function (input, callback (parameter))



It is not clear it? No problem, we see a practical example using the library function whose signature is array_walk:

 



 This feature applies to each element of the array $ callback $ funcname ($ userdata omit which is optional).

 

Prior to version 5.3 of PHP to use it we should write for example:






 $ Array = array ("Rick", "George", "Matthew");







 echoEach function ($ item) {



  



 echo $ item.

 



 "<br />";







 }









 array_walk ($ array, "echoEach");



Let's see how it changes with the use of lambda:






 $ Array = array ("Rick", "George", "Matthew");







 array_walk ($ array, function ($ item) {



  



 echo $ item.

 



 "<br />";







 });



For both versions, the output will be:






 Rick







 George







 Matthew



Another example, array_filter function, which accepts an array as input and a callback signature:






 array_filter array (array $ input [, callback $ callback])



We use anonymous functions:






 $ ArrayNum = array (1, 3, 6, 5, 2, 8);







 $ Filtered = array_filter ($ arrayNum, function ($ item) {



  



 return $ item> 2;







 });









 print_r ($ filtered);



The output:






 Array







 (



  



 [1] => 3



  



 [2] => 6



  



 [3] => 5



  



 [5] => 8







 )



That is a filtered array for values ​​greater than 2.

What do we gain? In the code readability and elegance.

In the same category ...
E-Learning
Linux (Course) Linux (Course)
Complete guide to open-source system. From 49 €.
MySQL (Course) MySQL (Course)
Management of open-source database. From 39 €.
PHP (Course) PHP (Course)
Full course for creating dynamic Web sites. From 49 €.
Sponsored Links