Anonymous functions(Lambda) are PHP features which we do not use often but they can be really useful in certain situations like passing a function as an argument in another function, accessing a variable which is declared outside the scope of the function etc.
I will be covering following concepts in article-
Lambda is useful because these are throw away functions that you can use once. Sometimes you need a function to do job but it’s not so common that you want to define it as a function but you also don’t want to make it available as a part of your code. So instead of having a function for that you can create a Lambda for that and use it once.
As a PHP developer, you must be knowing what a regular function is and how to define one? we can create a regular PHP function like this-
function myRegularFunction(){ //function definition here... }
When you define a regular function you give it a name(myRegularFunction in this cases). Now you can refer to this function using function name.
For example, you can call this function like this-
myRegularFunction();
Anonymous functions are similar to the regular function as they can contain the same type of code, they accept arguments, return values and all…
The key difference is – as the name implies – anonymous functions have no name. Here is an example of an anonymous function
function($argument1,$argument2){ //anonymous function definition goes here };
If you have noticed there are two key difference between a regular function and an anonymous function.
() which tells PHP that we are creating an anonymous function.
While the above code looks fine but it can not be called because this function doesn’t have any name. This function cannot be referred anywhere but you can do a lot of handy things with it-
While creating an anonymous function, it can also be assigned to a variable just like any other value. Here is an example-
$addition=function($arg1,$arg2){ return 'sum = '.$arg1+$arg2; };
once you have done that you can call this function with a variable name like-
echo $addition(20,50);
the output will be
sum = 70
Or even we can store multiple anonymous functions to an array like this-
//storing 5 anonymous function to an array $myarray = array( function(){ echo "this is 0th index function"; }, function(){ echo "this is 1st index function"; }, function(){ echo "this is 2nd index function"; }, function(){ echo "this is 3rd index function"; }, function(){ echo "this is 4th index function"; } );
Now we can decide which function to call at runtime. we can call any function like this
echo $myarray[3] //output- this is 3rd index function
One common use of the anonymous function is to create a simple inline callback function. A callback function is a function that you can pass to another function as an argument. Once you access your callback function the receiving function can use it whenever it needs to.
Many PHP built-in functions accept callback or you can create your own function which accepts callback function.
Let’s see some of the built-in function and understand their functionality
Using array_map() function to run a callback function on each element of the function
array_map() function accept a callback function and an array as argument. It iterates through every element of the array and applies the callback function to each element. Your callback function needs to return a value which will replace the array value and array_map return the modified array.
NOTE: array_map() works on a copy of array you pass to it. The Original array remains untouched.
Here is example-
//without callback function $num_array = array(1,2,3,4,5); foreach ($num_array as $key => $value) { $new_array[]=$value*$value; } print_r($new_array);
this will output-
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
when we use a regular function a a callback function in array_map()
//with regular callback function function square($num){ return $num*$num; } $new_array=array_map('square', $num_array); print_r($new_array);
this will also output the same result.
Using anonymous function as callback
$new_array = array_map(function($num){ return $num*$num; }, $num_array); print_r($new_array); print_r($num_array);
this will output-
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 ) Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
as you can see there is no change in $num_array array. its content remained same.
A closure is same as the lambda apart from it can access the variable which is created outside of its scope or are not in its perimeter.
Confusing… right?
let’s take an example to get it clear-
Simple closure example
We are creating a simple closure using an anonymous function:
//define a regular variable $user='Peter'; //create a closure using anonymous function $message=function() use ($user){ echo 'hello'. $user; } $message();//output - hello Peter
As you can see above $user variable is defined outside and is not accessible inside any function but in this case, closure is able to access it because it was declared in the use clause of the Closure function definition.
If you alter $user variable within closure it will not affect the original value. its value will still be “Peter”. If you want to alter the original value you can use the reference to $user as &$user in closure as below
$message=function() use (&$user){ echo 'hello'. $user; }
So now you have a clear picture of Lambda and closure. These were introduced in PHP 5.3. If you are familiar with javascript and jquery you will see anonymous functions are used a lot in these. Once you got the picture of these it will be easy for you to understand the code because you not only understand how it is written but also understand why it is written like this.
I am the owner of acmeextension. I am a passionate writter and reader. I like writting technical stuff and simplifying complex stuff.
Know More
Comments
This is a really good explanation of what anonymous are functions in PHP and why use them.
Great stuff, thanks!
Hello dear SUNIL KUMAR
Wow.. thats grate, Thank you very very much.
do you have any online PHP learning course or any your handout of PHP, JS, JQUERY …?
best regard
Hadi
Hi Hadi,
Thanks for your appreciation. Right now I don’t have any online course But there are a lot of course available in the market. Personally, I learn things by youtube videos.
Here is a better answer to the question “Why use them?”
Because it is a closure.
Which means you can hide information, such as business logic.
Within the closure you can do things whereby the client is not aware of.
It is a callable.
When you make a callable available in a scope,
then the only thing the calling-client knows it can call it, no more.
Lazy loading.
You can pass the closure where ever you want but it only action when it is called.
Awesome Thnks to this tut.
I learn something new ‘Closures’
There’s a typo on the penultimate code box when calling the $nessage ($message) variable.
Thanks, Rodrigo
Updated the post.
It was one of the easiest articles to learn, thanks a lot
Thanks for this article.
I switched to PHP7 and it complained about create_function() being deprecated in one of the plugins.
Using anonymous function solved the issue.
you explained extremely well…..thank you so much