PHP Anonymous Functions [WHAT and WHY]

By: Sunil Kumar |  In: PHP  |  Last Updated: 2018/05/12

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-

  • Why use anonymous functions.
  • What anonymous functions are and how to create them.

Why would you want to use Lambda?

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.

Anonymous functions(Lambda)

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.

  • There is no function name(between function keyword and the opening parenthesis() which tells PHP that we are creating an anonymous function.
  • There is a semicolon(;) after the function definition. This is because anonymous functions definitions are expressions whereas regular function definition is code constructs.

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-

  • You can assign it to a variable and can call it using the variable name. Even you can store a bunch of different anonymous functions in a single array.
  • You can pass this function to another function as a parameter. This is known as Callback.
  • Return it from within an outer function so that it can access the outer function’s variables. This is known as a closure.

Assigning anonymous function to variables

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

Using anonymous function as callback

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.

Creating Closures with anonymous functions

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;

}

$nessage();//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;

}

Conclusion

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.

Comments


  • Leave a Comment

    Your email address will not be published.

    *


    %d bloggers like this: