Why use anonymous function? [duplicate]

2019-02-01 05:06发布

问题:

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.

回答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.



回答2:

It is useful especially for callbacks:

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


回答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.



回答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.



回答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.



回答6:

If you need to create a callback (to make a concrete example, lets say its a comparison function for usort) anonymous functions are usually a good way to go. Particularly if the definition of the function is dependent on a few inputs (by this i mean a closure, which is NOT synonymous with anon function)

function createCallback($key, $desc = false)
{
    return $desc ? 
       function($a, $b) use ($key) {return $b[$key] - $a[$key];} :
       function($a, $b) use ($key) {return $a[$key] - $b[$key];};
}


usort($myNestedArray, createCallback('age'));  //sort elements of $myNestedArray by key 'age' ascending
usort($myNestedArray, createCallback('age', true); //descending


回答7:

There are times when you MUST use a function. Thus closures keep code clean by not having to fill your libraries with function declarations that are only used in one place. Closures are similar to style="" and classes in CSS. Sure you can create a boatload of classes for every single one off style you have, or you can embed them in place since you do not use it elsewhere and decrease the bloat of your CSS files.

It's not a necessity, though, so if you feel the need to explicitly declare functions you are free to do that.



回答8:

In my opinion, anonymous functions are best used as callbacks for functions. Many of the php array functions will use these as parameters.

They could also be used in observer / event listener patterns.



回答9:

Using jQuery/Javascript you can use it to define custom event callbacks. Take a look at how the jQuery core handles AJAX.

Example of jQuery using anonymous functions for event callbacks:

$.ajax({
  url: 'ajax/test.html',
  complete: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

Other events w/ custom callbacks are beforeSend, error, success. You can take full advantage of this flexible event callback system when authoring custom plugins