Only some days ago PHP.net introduced 5.3.0RC1 version, but future features have been known for quite a while. Namespaces and lambda functions (+ closures) are most anticipated, because they’ll increase flexibility and good-looks of code a lot. Today I’m going to try to prove why lambda functions are so useful.
Because of “Functional Programming” course I had in university, I love lambda functions. At first they seemed a little bit strange, but hey – in Haskell you write:
Input: map (\x => x*3) [1,2,3,4] Output: [3,6,9,12]
No need to create for loops (which doesn’t exists in Haskell at all) and code is much more flexible. Functional languages allows creating functions which accepts functions as arguments, not only integers or floats. That’s why most functions are very short, but are very easily connectable together.
I think one the best examples of lambda functions usefulness is sorting. Image this scenario: $books collection holds books information and you need to sort it by title; author; publish year and author; publish city and title. How you are going to do it? It’s easy and you probably would write something like this:
// Sort by title $books->sortByTitle('ASC'); // Sort by publisher year, author $books->sortByPublishYear('DESC')->sortByAuthor('ASC');
However, it looks good and does work just fine, but it’s not very practical – you need to create functions for all keywords (title, author, publish year, etc.). You may argue, that __call() can be used and that’s absolutely true, but it’s even harder to maintain and code it, still usable though.
Nevertheless, 5.3 version of PHP introduces lambda functions (also called anonymous functions), which can simplify your work a lot (I haven’t tried running this code):
// Sort by book title $books->sort( function ($book1, $book2) { return strcmp($book1->title, $book2->title); }); // Sort by publisher year, author $books->sort( function ($book1, $book2) { if ($book1->publish_year == $book2->publish_year) return strcmp($book1->author, $book2->author); return strcmp($book2->publish_year, $book1->publish_year); });
It’s a little bit harder to read and maybe understand, but basically you can pass whatever comparison function you’d like. Sort function can use simple for-loop-inside-for-loop or usort and compare all elements with your function
Lambda functions are not replacement for __cal() and should be used cleverly, search and filtering with lambda functions is only one example of how useful they are. In short, lambda functions allows you to create small dynamic functions which can be used to expand and modify normal functions behaviour.







