Why and how do you use anonymous functions in PHP?
Asked Answered
L

6

46

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) {};
$container->db       = function($container) {};
$container->memcache = function($container) {};
Luxuriant answered 9/3, 2010 at 20:27 Comment(3)
Man, I don't get that DependencyInjection usage at all.Blackandblue
@Tchalvak, why? As for me it's really easy to implement and to use. Is there any traps?Luxuriant
@Luxuriant $container = new DependencyInjectionContainer(); it has nothing to do with anonymous functionsKearns
G
91

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);
Geisha answered 9/3, 2010 at 20:36 Comment(1)
That seems to be most consist answer I ever found about purpose of anonymous functions. It underline the fact, that for most one-time / one-place solutions, anonymous functions allows you to keep code right, where it is used, without need to define it in one places and call in another. This becomes extremely useful, if you have such one-time functions counted in hundreds or thousands in one project.Astrodynamics
R
25

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
)
Reimer answered 9/3, 2010 at 21:20 Comment(1)
@Reimer So.. aside from working with callback functions, anonymous function are useless? I just don't get what the hype was aboutBerkeleian
S
10

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

Stereophotography answered 9/3, 2010 at 20:33 Comment(2)
Hmmm, for the php documentation, that is indeed a good article.Blackandblue
Yes indeed very well explainedFrutescent
U
4

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.

Uncle answered 1/6, 2014 at 23:14 Comment(2)
Hello @brasofilo, could you please explain a little more? I'm not able to understand the difference.Minotaur
@Minotaur difference is as example when you register: $di->add('service', new Object()); the instance of object is stored in di container. When you will create $di->add('service', function(){ return new Object(); }); the instance of object is created on "request" so difference is that you can have registered all services in di and the registered services will not consupt memory, because instances are not created yet. In many cases devs, registering services to di but on every request is service created, and this process slowing execution. When you have anonymous function nothing is created.Uncle
S
2

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.

Smallclothes answered 9/3, 2010 at 20:30 Comment(0)
H
0

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.

Homeland answered 24/1, 2018 at 7:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.