Anonymous functions, is a function that allows the creation of a function without any specific name. We can use it as follows:
1-Assign it to a variable, then call it later using the variable's name.
2-We can store an array of different anonymous functions in a single array.
3-Pass the anonymous function to another function that can be used later generally
known as a callback.
4-The body of anonymous function is ended with a semicolon.
1- Assigning variable:
$anonymous = function( $name) {
return ( "Hello, $name!" );
};
After assignment we can call the function using the variable name
$anonymous(John);
OUTPUT: Hello John!
2- Storing anonymous functions in an array:
$anonymous =array(
function() {
echo "Hello, first function called!" ;die;
},
function() {
echo "Hello, second function called!" ;die;
},
function() {
echo "Hello, third function called!" ;die;
},
function() {
echo "Hello, fourth function called!" ;die;
}
);
$order = rand( 0, 3 );
$anonymous[$order]();
Random OUTPUT:
Hello, fourth function called!
Hello, first function called!
Hello, third function called!
3-Passing an anonymous function as a callback:
$anonymous = function( $name) {
echo "Hello, $name! </br>";
};
$list = array('John','Ravi','Jayant','Surit','Rakesh');
$listing = array_walk($list, $anonymous);
OUTPUT:
Array
(
[0] => Hello, John!
[1] => Hello, Ravi!
[2] => Hello, Jayant!
[3] => Hello, Surit!
[4] => Hello, Rakesh!
)
0 Comment(s)