Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and how do you use anonymous functions in PHP?

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) {}; 
like image 722
Kirzilla Avatar asked Mar 09 '10 20:03

Kirzilla


People also ask

Why do we use anonymous functions?

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.

What is anonymous function explain with example?

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.

How is anonymous function different from normal function in PHP?

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.

Why are anonymous functions frequently used with event handlers?

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.


1 Answers

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); 
like image 113
Gumbo Avatar answered Oct 06 '22 00:10

Gumbo