Anonymous function in PHP

Anonymous function (aka Closure, Lambda) in PHP are very useful, it allows us to do functional programming (well in a sense we can create higher order function ).  Here are some usages of anonymous function.

1. Create a Lambda function:

Anonymous function does not have any name but we can assign it to a variable.

2. Use as function argument:

We can use anonymous function as function argument, php also provides a callable type hint that we can use. Here is an example to create a decorator using anonymous function.

3. Use as function return value:

We can also use anonymous function as function return value, welcome to function currying.

4. Built-ins:

Many built-in array functions accepts callable ex. array_filterarray_map, array_reduceusort etc

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s