AnchovyLegend
AnchovyLegend

Reputation: 12538

Use of Anonymous Functions in PHP

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');
?>

Upvotes: 2

Views: 219

Answers (3)

Anthony
Anthony

Reputation: 37065

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.

Upvotes: 1

Alexey Lebedev
Alexey Lebedev

Reputation: 12197

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']);
});

Upvotes: 4

deceze
deceze

Reputation: 522101

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) { ... });

Upvotes: 2

Related Questions