Home » Php » Why and how do you use anonymous functions in PHP?

Why and how do you use anonymous functions in PHP?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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) {};
How to&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);

Answer:

Anonymous functions are available from PHP 5.3.

Anonymous functions have been available in PHP for a long time: create_function has been around since PHP 4.0.1. However you’re quite right that there is a new concept and syntax available as of PHP 5.3.

Should I use them or avoid them? If so, how?

If you’ve ever used create_function before, then the new syntax can simply slip right in where you used that. As other answers have mentioned, a common case is for ‘throwaway’ functions where they are to be used just once (or in a single place at least). Commonly that comes in the form of callbacks for the likes of array_map/reduce/filter, preg_replace_callback, usort, etc..

Example of using anonymous functions to count the number of times letters appear in words (this could be done in a number of other ways, it is just an example):

$array = array('apple', 'banana', 'cherry', 'damson');

// For each item in the array, count the letters in the word
$array = array_map(function($value){
    $letters = str_split($value);
    $counts  = array_count_values($letters);
    return $counts;
}, $array);

// Sum the counts for each letter
$array = array_reduce($array, function($reduced, $value) {
    foreach ($value as $letter => $count) {
        if ( ! isset($reduced[$letter])) {
            $reduced[$letter] = 0;
        }
        $reduced[$letter] += $count;
    }
    return $reduced;
});

// Sort counts in descending order, no anonymous function here :-)
arsort($array);

print_r($array);

Which gives (snipped for brevity):

Array
(
    [a] => 5
    [n] => 3
    [e] => 2
    ... more ...
    [y] => 1
)

Answer:

Maybe you could just read PHP’s article on Anonymous Functions. It’s actually pretty good.

Answer:

Anonymous functions can be very useful in creating function into DI container too, for example “bootstrap.php”:

//add sessions
$di->add("session",function(){ return new Session(); });
//add cache
$di->add("cache",function(){ return new Cache(); });
//add class which will be used in any request
$di->add("anyTimeCalledClass", new SomeClass());

Example with usage params, and next variables

$di->add("myName",function($params) use($application){
      $application->myMethod($params);
});

So here you can see how you can use anonymous functions to save memory and load of server. You can have defined all important plugins, classes in di container, but instances will be created just if you need it.

Answer:

A typical use of anonymous functions is callback functions. For example, you could use them for callback from sort algorithms such as in function uksort ( http://lv.php.net/uksort ) or replacing algorithms such as preg_replace_callback ( http://lv.php.net/manual/en/function.preg-replace-callback.php ).
Have not tried it myself in PHP, so this is just a guess.

Answer:

Here is sample example of using using anonymous functions in Php

$suppliers=['add1'=>'nodia','add2'=>'delhi', 'add3'=>'UP'];
 $getAddress = function($suppliers){ $address=[];
 for($i=1;$i<5;$i++){
  if(array_key_exists('add'.$i, $suppliers))
    $address[]=$suppliers['add'.$i];
  }
 return $address;};
 print_r($getAddress($suppliers));

In above example we have written anonymous functions that check if a key exists in inputted array. If it exists then it will put that into output array.