PHP Anonymous Functions: What Are They, and Why Use Them?

  You are currently not logged in. You can view the forums, but cannot post messages. Log In | Register

10-Dec-12 00:00
This is a forum topic for discussing the article "PHP Anonymous Functions: What Are They, and Why Use Them?":

Learn how to create and use anonymous functions, callbacks and closures in PHP.
10-Dec-12 22:42
Thanks for article...
Some of it is a bit over my head, but I get the general gist!
One thing that has me confused is the usort example.
Should this line:
return ( $personA["age"] < $personB["age"] ) ? -1 : 1;
Have "name" for $personA ?
Cheers, Dave
11-Dec-12 13:39

That line is the equvalent of

if($A < $B) {
return -1;
} else {
return 1;

So long, and thanks for all the fish.
10-Jun-14 06:26
Hello. Thanks for all your nices tutorials. I am learning a lot.

I Get a warning in this line
print_r( array_map( nameToGreeting, $names ) );

And it dissapear if I write this
print_r( array_map( 'nameToGreeting', $names ) );

the difference are the quotes 'nameToGreeting'

Thanks a lot again
10-Jun-14 06:33
Hi Jarimos,

By putting the function name in quotes you are just masking the fact that it must be missing ?

It looks like this in the article...

// Create a regular callback function...
function nameToGreeting( $name ) {
return "Hello " . ucfirst( $name ) . "!";

Check your syntax and ensure it is accurate!

HTH, Dave
14-Feb-17 16:47
Hi there,

You say "Note that, by this point, getGreetingFunction() has finished running. In normal circumstances, its local variable, $timeOfDay, would have fallen out of scope and disappeared. However, because we've created a closure using the anonymous function (now stored in $greetingFunction), the anonymous function can still access this $timeOfDay variable.".

I cant shake off the idea that $greetingFunction is a reference to getGreetingFunction(). You say getGreetingFunction has finished running but isnt it so that the named function is called every time the variable $greetingFunction is used? I cant get my head around the fact that the named function as well as the anonymous function runs whenever the variable is used (since it references the named function).
12-Jun-17 08:07

Can I call anonymous function inside another anonymous function?

For example:

$function1 = function() use() {
return 2;
$function2 = function() use() {
return 2 * $function1();
echo $function2();
12-Jun-17 21:29
Provided the functions are not reiterative (calling an instance of themselves), there should be no problem.

So long, and thanks for all the fish.

New posts
Old posts

Follow Elated