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) {};
The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.
In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
Anonymous functions are similar to regular functions, in that they contain a block of code that is run when they are called. They can also accept arguments, and return values. The key difference — as their name implies — is that anonymous functions have no name.
More generally, the point of using anonymous functions is that they do not require a name, because they are "event handlers" bound to a specific event on a specific object. In this case, the object is the entire Document Object Model, and the anonymous function executes when the entire DOM has loaded.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With