Why use anonymous function? [duplicate] Why use anonymous function? [duplicate] php php

Why use anonymous function? [duplicate]


I would say that anonymous functions show their beauty when there is good library classes/functions that use them. They are not that sexy by themselves. In the world of .net there is technology called LINQ that makes huge use of then in very idiomatic manner. Now back to PHP.

First example, sort:

uasort($array, function($a, $b) { return($a > $b); });

You can specify complex logic for sorting:

uasort($array, function($a, $b) { return($a->Age > $b->Age); });

Another example:

$data = array(         array('id' => 1, 'name' => 'Bob', 'position' => 'Clerk'),         array('id' => 2, 'name' => 'Alan', 'position' => 'Manager'),         array('id' => 3, 'name' => 'James', 'position' => 'Director') ); $names = array_map(         function($person) { return $person['name']; },         $data );

You see how nicely you can produce array of names.

Last one:

array_reduce(   array_filter($array, function($val) { return $val % 2 == 0; },   function($reduced, $value) { return $reduced*$value; })

It calculates product of even numbers.

Some philosophy. What is function? A unit of functionality that can be invoked and unit of code reuse. Sometimes you need only the first part: ability to invoke and do actions, but you don't want to reuse it at all and even make it visible to other parts of code. That's what anonymous functions essentially do.


It is useful especially for callbacks:

array_walk($myArray, function($value, $key) {   // do something});


You normally use anonymous functions for functions which you need only once. This way you do not pollute the function namespace and don't invent strange function names like array_walk_callback1.