Why use anonymous function?

20,126

Solution 1

I would say that anonymous functions show their beauty when there is good library classes/functions that use them. They are not that sexy by themselves. In the world of .net there is technology called LINQ that makes huge use of then in very idiomatic manner. Now back to PHP.

First example, sort:

uasort($array, function($a, $b) { return($a > $b); });

You can specify complex logic for sorting:

uasort($array, function($a, $b) { return($a->Age > $b->Age); });

Another example:

$data = array( 
        array('id' => 1, 'name' => 'Bob', 'position' => 'Clerk'), 
        array('id' => 2, 'name' => 'Alan', 'position' => 'Manager'), 
        array('id' => 3, 'name' => 'James', 'position' => 'Director') 
); 

$names = array_map( 
        function($person) { return $person['name']; }, 
        $data 
);

You see how nicely you can produce array of names.

Last one:

array_reduce(
   array_filter($array, function($val) { return $val % 2 == 0; },
   function($reduced, $value) { return $reduced*$value; }
)

It calculates product of even numbers.

Some philosophy. What is function? A unit of functionality that can be invoked and unit of code reuse. Sometimes you need only the first part: ability to invoke and do actions, but you don't want to reuse it at all and even make it visible to other parts of code. That's what anonymous functions essentially do.

Solution 2

It is useful especially for callbacks:

array_walk($myArray, function($value, $key) {
   // do something
});

Solution 3

You normally use anonymous functions for functions which you need only once. This way you do not pollute the function namespace and don't invent strange function names like array_walk_callback1.

Solution 4

Perhaps most obvious reason is the use of callbacks. Take usort() function for example. There's no point introducing a one-line function, that will be used once and once only. Anonymous function (usually) fits better this task.

Solution 5

You can pass anonymous functions around by saving them in a variable.

$a=function() {
    echo 'hello world';
};

This means you can also use them more than once.

Share:
20,126

Related videos on Youtube

Shoe
Author by

Shoe

I like C++, Haskell, PostgreSQL, Prolog and you.

Updated on April 17, 2020

Comments

  • Shoe
    Shoe about 4 years

    Possible Duplicate:
    How do you use anonymous functions in PHP?

    Why should i use an anonymous function? I mean, what's the real deal using it? I just don't really get this. I mean, you use function to make the code more clean or to use it more than once. But Anonymous functions just don't do neither the first nor the second. I googled them and i couldn't find anyone asking the same problem.

    • Bradley Kreider
      Bradley Kreider over 13 years
      Can you remove closures from the title? It's slightly tangential to the meat of your question.
    • jon_darkstar
      jon_darkstar over 13 years
      @rox0r - you really think closures are unrelated? seemed appropriate to me so i incorporated into my answer in way i hope is useful for demonstration. obviously you can have lambda funcs without closures, but not vice-versa
    • Bradley Kreider
      Bradley Kreider over 13 years
      @jon: I think they are related, but his intent seemed to be focused on just named vs anon. functions. I think it is good that you mentioned closures, i just thought it was misleading in the title.
  • Shoe
    Shoe over 13 years
    But if i use that function just once why shouldn't just don't declare any functions at all? Neither the normal nor the anonymous one?
  • gnarf
    gnarf over 13 years
    Hopefully you never invent those strange function names. Things like returnUsefulDataFromArray would be more useful :)
  • gnarf
    gnarf over 13 years
    And do you really want your HTML polluted with tags describing presentation, as opposed to content?
  • methodin
    methodin over 13 years
    Anonymous functions help when you MUST USE A FUNCTION - like in usort, array_map etc... in these cases traditionally you would have to create a function somewhere in the code and pass the name of the function in. With anonymous functions you can just declare it on the fly. It also helps with callbacks. Your examples seem to indicate you are thinking of anonymous functions as just ways to group code - which they can be, but that's not the real purpose of them.
  • Bradley Kreider
    Bradley Kreider over 13 years
    @charlie Sometimes you need to have a function to pass in as a parameter. That's why people mention callbacks. When callbacks are used, you have to pass a function to the callback.
  • Andrey
    Andrey over 13 years
    how is it better then foreach? This is meaningless example. It shows something that can be done using another construct even easier. it doesn't show usefulness of anonymous function. really.
  • Shoe
    Shoe over 13 years
    Why don't just declare a function then?
  • Andrey
    Andrey over 13 years
    "more than once". Can't you use regular function more then once?
  • Shoe
    Shoe over 13 years
    Edit your last piece of message, please.
  • bcosca
    bcosca over 13 years
    You ought to remember that declared functions are global, while anonymous functions are not. You don't want to pollute the global namespace with use-once and trivial functions
  • Shoe
    Shoe over 13 years
    @rox0r I got that, but you could also use a string with the function name as callback. Anyway thanks, know i know.
  • jon_darkstar
    jon_darkstar over 13 years
    gladly would, but im not sure what you mean
  • netcoder
    netcoder over 13 years
    The OP didn't ask what was better. It asked what is it useful for. The answer: callbacks. If you want to provide 1000 examples, feel free to do it in your own answer.
  • jon_darkstar
    jon_darkstar over 13 years
    +1 for non-trivial use and for composing reduce and filter
  • Shoe
    Shoe over 13 years
    The last 2 lines should be code right?
  • jon_darkstar
    jon_darkstar over 13 years
    oh yeah guess so, i was thinking of createCallback as the real 'meat' of it, but i suppose i should make them code too
  • Bradley Kreider
    Bradley Kreider over 13 years
    @charlie: Do you mean function name instead of string? Yes. I was responding to "why declare any functions at all" that is above.
  • Andrey
    Andrey over 13 years
    Right. "It asked what is it useful for." in your example they are not useful at all. I am not saying that you should provide 1000 examples. One could be enough, but a representative and relevant one.
  • netcoder
    netcoder over 13 years
    Also, variable functions can be destroyed using unset, while global functions cannot.
  • netcoder
    netcoder over 13 years
    @Andrey: If you don't feel my answer is useful enough, don't upvote it, and provide what you think is a better answer. End of story.
  • Andrey
    Andrey over 13 years
    @jon_darkstar in C# it is trivial :) it is more functional style.
  • Derek Adair
    Derek Adair over 13 years
    didn't see that it was tagged w/ php. woops
  • James Spence
    James Spence about 9 years
    Just stumbled upon this in my own travels, it was immediately helpful five years later. +1
  • CragMonkey
    CragMonkey almost 9 years
    You said "a closure... is NOT synonymous with anon function", however, the PHP manual specifically states otherwise ("Anonymous functions, also known as closures,..." php.net/manual/en/functions.anonymous.php ). What distinction do you see?
  • jon_darkstar
    jon_darkstar almost 9 years
    top answer here is a good explanation: stackoverflow.com/questions/4912116/…
  • Honinbo Shusaku
    Honinbo Shusaku almost 9 years
    @netcoder What is the use of destroying a variable, except for freeing up the name? Is unset similar to myVariable = null; in Java, where it will eventually free up memory as well?
  • netcoder
    netcoder almost 9 years
    @Abdul: Scoping is very different in PHP vs Java. In fact, in PHP scoping is limited to global scope and function scope. e.g.: { $foo = "bar"; } echo $foo; works in PHP. { String foo = "bar"; } System.out.println(foo); doesn't in Java. Un-setting variables can be useful to prevent polluting the scope that may eventually introduce programming errors. That applies to both variables and variable functions.