PHP: Anonymous functions and callbacks

Anonymous functions are one of the nice and useful feature in PHP that is widely being used. Anonymous functions facilitate to write well structure and more readable code. It can also be used as callbacks.

What is anonymous function?

Anonymous functions are similar to regular functions and also accept arguments and return values. The key differences between both that anonymous functions have no specified name and can be assigned in a variable. These functions are most useful as callbacks. See following example to create a simple anonymous function:

<?php
$func = function($name){
	return $name;
};

echo $func('The Elementary');
?>

Since an anonymous function is an expression, so it can be used for various and useful ways.

Assign to a variable

An anonymous function can be assigned in a variable, even can be stored bunch of different anonymous functions in a single array.

<?php
$greeting = function($name){
	return 'Hello '.$name. ' !';
};

//Call the anonymous function
echo $greeting('William');
echo '<br>';
echo $greeting('Sachin');
?>

Output will be:
Hello William !
Hello Sachin !

Now, we store anonymous functions inside an array. See following example:

A user has three choices(1, 2, 3) for a vendor machine. There are three type of items Water bottle, Juice and Sweets.

<?php
$machine = [
	1=> function(){
		echo "Got Water bottle<br>";	
	},
	2=> function(){
		echo "Got Juice<br>";	
	},
	3=> function(){
		echo "Got Sweets<br>";	
	},
];

$choice = 1;
echo $machine[$choice]();
$choice = 2;
echo $machine[$choice]();
$choice = 3;
echo $machine[$choice]();
?>

if $choice = 1 then output will be “Got Water bottle”.
if $choice = 2 then output will be “Got Juice”
if $choice = 3 then output will be “Got Sweets”

Use anonymous functions as closure

A closure is nothing but an anonymous function that uses one or more variables and accesses when is is called. In other words, a closure has the ability to interact with variables from the outside environment.

<?php
$greetingWord = "Hello";

$greeting = function($name) use($greetingWord) {
	return $greetingWord.' '.$name;
};

echo $greeting('Sachin');

//Output:
//Hello Sachin
?>

Callbacks

A callback function is passed as an argument to another function. Many built-in functions accept callbacks. Let’s take a PHP ‘s array function array_map().

Use inline

<?php

$numbers = [30, 40, 10, 60, 50];
print_r(array_map(function{
	return $no + 5;
    },  $numbers)
);
?>

Output will be:
Array ( [0] => 35 [1] => 45 [2] => 15 [3] => 65 [4] => 55 )

Use a normal function as callback

A normal function can also be used as callback. In this scenario, name of function is passed as callback. See the following example with array_filter() function. In this example, we filter numbers that are divisible by 2.

<?php
function checkVisibility($no)
{
    if($no%2 == 0){
        return $no;
    }
}

$numbers = [10, 20, 15 , 17, 18, 7];
print_r(array_filter($numbers, 'checkVisibility'));
?>

Output will be:
Array ( [0] => 10 [1] => 20 [4] => 18 )

Use built-in functions as callback

<?php
$names = ['Sachin', 'Tom', 'William', 'Rohit'];

print_r(array_map('strtoupper', $names));

//Output:
//Array ( [0] => SACHIN [1] => TOM [2] => WILLIAM [3] => ROHIT )
?>

<?php
//Trim all post data
print_r(array_map('trim', $_POST));


//Remove all HTML Tags from post data
print_r(array_map('strip_tags', $_POST));
?>

Use callbacks with classes

Following examples help you to understand use of callbacks with classes.

Use callbacks with normal method

Suppose , there is an array of number elements and need to add 5 to each element.

<?php
class Number {
    public function adding5($no)
    {
        return $no + 5;
    }
}

$noObj = new Number();
$nos = [5, 40, 3, 11, 77];
print_r(array_map([$noObj, 'adding5'], $nos));

//OR

print_r(array_map(['Number', 'adding5'], $nos));
?>

Output will be:
Array ( [0] => 10 [1] => 45 [2] => 8 [3] => 16 [4] => 82 )

In array_map() function the first parameter is an array that has two elements, first object of class Number or class name self and second is method name(“adding5”) of class Number.

Now, take same example and use a class method as callback in another class method.

<?php
class Number {

    public function foo($numbers)
    {
        return array_map([$this, 'adding5'], $numbers);
    }
    public function adding5($no)
    {
        return $no + 5;
    }
}

$nos = [5, 40, 3, 11, 77];
$noObj = new Number();
print_r($noObj->foo($nos));
?>

In array_map() function the first parameter is an array that has two elements, first $this that indicates current class Number and second is method name(“adding5”) of class Number. Class method adding5() can also be private.

Use callbacks with static method
<?php
class Number {
    public static function adding5($no)
    {
        return $no + 5;
    }
}

$noObj = new Number();
$nos = [5, 40, 3, 11, 77];
print_r(array_map('Number::adding5', $nos));

//OR

print_r(array_map(['Number', 'adding5'], $nos));
?>

Hope you like this and enjoy coding.

If you have any questions or suggestions, let me know!