Why and how do you use anonymous functions in PHP?

Kirzilla picture Kirzilla · Mar 9, 2010 · Viewed 45.3k times · Source

Anonymous functions are available from PHP 5.3.
Should I use them or avoid them? If so, how?

Edited; just found some nice trick with php anonymous functions...

$container           = new DependencyInjectionContainer();
$container->mail     = function($container) {};
$conteiner->db       = function($container) {};
$container->memcache = function($container) {};

Answer

Gumbo picture Gumbo · Mar 9, 2010

Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:

$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { return $val % 2 == 0; });
$arr_square = array_map(function($val) { return $val * $val; }, $arr);

Otherwise you would need to define a function that you possibly only use once:

function isEven($val) { return $val % 2 == 0; }
$arr_even = array_filter($arr, 'isEven');
function square($val) { return $val * $val; }
$arr_square = array_map('square', $arr);