2

This question may be silly. But an anonymous function does not really seem that anonymous to me. Maybe I am understanding it wrong, but an anonymous function must be stored in some variable, so it can later be referenced by this variable. If this is the case, what makes the below function so anonymous or so different than a regular function (other than the ability to store the function itself in a variable)? Or to word it differently, how is an anonymous function MORE useful than a regular function?

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

function greet($name)
{
     printf("Hello %s\r\n", $name);
}

$greet('World');
$greet('PHP');

greet('World');
greet('PHP');
?>
5
  • 4
    They are helpful when you need a one-off function for something, such as callbacks. And, you don't need to have them in a variable to use as a callback, but there is nothing wrong with putting them in one. Commented Dec 27, 2013 at 16:50
  • Anonymous just means the function has no name... Commented Dec 27, 2013 at 16:52
  • @Digital Chris, I get your point, the function declaration doesn't have a name, however, it cannot be used throughout your application without first assigning it to a variable, correct? so in some sense, it must have some name, in order to be reusable, doesn't it? Otherwise it will only be useful in one instance of your application... Commented Dec 27, 2013 at 16:57
  • 1
    "Only in one instance..." - And that's typically exactly the point. Commented Dec 27, 2013 at 17:07
  • @AnchovyLegend - If you need the function to be global so it can be reused, then you should create a global function. I have seen tons of jquery chaining blocks where the anonymous callback function used in several places is virtually identically and should be defined globally, but the inline anonymous function has simply become a coding pattern. On the other hand, if the callback function is never going to be reused outside the one place it's needed, then having a named, reusable function is not as valuable as having the function right where it's used and needed when debugging/updating. Commented Dec 27, 2013 at 17:29

3 Answers 3

4

Imagine you want to sort a list of users by username. Instead of defining a named comparison function that you're only going to use once, you can use an anonymous function:

usort($users, function($a, $b) {
    return strcmp($a['username'], $b['username']);
});
Sign up to request clarification or add additional context in comments.

Comments

2

The function itself has no name, as you show in your example you can still create a "real" function with the "same name". They're usually used like this as callbacks, which may seem more "anonymous":

foo(function ($bar) { ... });

2 Comments

maybe I am missing the point, but if the anonymous function is only used in one instance of your application and your function say contains 5 lines of code. Why not simply include these 5 lines without creating the lambda function? Is including the lambda function solely for clarity, to say 'this block of code is a function'?
Example usage: $names = array_map(function ($user) { return $user['name']; }, $users). This one liner extracts all name keys out of a multidimensional array and is a great example for callbacks. The alternative here would have been 4 lines of foreach loops with extra variables clobbering the scope. In this case you do not want to create a new global function, but this function is going to be called many many times. Maybe learning a bit of functional programming (Haskell, Erlang, advanced Javascript) would help you see the usefulness of the style overall.
1

One useful thing about anonymous (or lambda, if you prefer) functions is that they allow for creating your callback function inline with the code that needs it, rather than setting up a global function that will only be used in that one context. For instance:

$foo = native_function($bar, callback_function);

can be instead :

$foo = native_function($bar, function() { return $bar + 1; } );

Another handy thing about anonymous functions is that the variable you set it to calls that function every time, so it's not storing a value, but deriving it instead. This is great if a variable represents some derived value. Example:

$tax = .1;
$total = function() use (&$price, &$tax) { return $price * (1 + $tax); };
$price = 5.00;

echo $total();  // prints 5.50

$price = $price + 1;

echo $total(); // prints 6.60

$discount = $total() - 2;

echo $discount; // prints 4.60;

Instead of having to call a function like get_total and passing it $price every time, you interact with a variable that is always set to the newest value because it derives that value every time with the lambda function.

9 Comments

Your last example is non-functional (no pun intended).
Echoing variable with anonymous function, does not call this function. Also variables inside are not inherited from defining scope. Your whole example is not working in PHP, looks rather like JavaScript.
@deceze - I just tested in php, you are correct. I think it works with js, though, is that right? I have done this before, I'm almost positive. I just assumed it was the nature of anonymous functions. Let me know ASAP and I'll either remove or update to show it as js example, since it is incredibly useful in the second sense.
Honestly, that's a pretty aweful use of anonymous functions.
@deceze - oh, that was more about showing it as a standalone variable, but I agree that passing it a value would be more appropriate. According to the wiki article on anonymous functions, this would be a currying application of an anonymous function, where one variable is provided while the other variable is fixed. The $price argument would make more sense if instead it was derived in the function and the $total() was passed an array of items which each have a price and can be added to, so that $total($items) would sum the prices and apply the tax, etc.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.