Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

What is the difference between Normal function vs Anonymous Function?

I am totally confused about anonymous function, is this a kind of some hidden function?

1 Answer

Benjamin Payne
Benjamin Payne
8,142 Points

Hey Vijesh,

An anonymous function is not hidden in any way. Think of an anonymous function as one that is passed around like any other scalar type (strings, ints, booleans etc.). In this way an anonymous function can be used as a function parameter and defined as an argument. Or assigned to a variable and be called using the variable name like $var(). Or used in an array or any place a scalar can be used. Anonymous functions can also be type hinted with the callable type hint on a function or method. Anonymous functions reference.

That being said, like all things in programming, knowing what something is, is only half the battle. Knowing when to use something is the other half. A perfect example of when to use an anonymous function is in closure based routes in frameworks like, Slim, Silex, and Laravel. These all utilize some form of closure based routes so that you can define functionality in a routes file and then what you defined as the controller for the route is handled later by the router. For example:

$app->get('/', function () use ($app) {
   echo "Hello World";
});

The second argument passed to the `get' method is an anonymous function. It will be called dynamically later in the execution life cycle by the router when the request URI matches the '/' pattern.

Hopefully that helps.

Thanks, Ben