PHP Anonymous functions, also known as closures, are a powerful feature of modern programming languages which allow developers to create functions without giving them a specific name, making them perfect for creating small, one-time use functions.

PHP has supported anonymous functions since version 5.3, and they have become increasingly popular in PHP development in recent years.

In this article, we will explore anonymous functions in PHP, how to use them, and why they are useful.

To learn more about functions, read this tutorial.

What are Anonymous Functions in PHP?

An anonymous function, as mentioned before, is a function without a specific name. In PHP, anonymous functions are created using the function keyword followed by parentheses that contain the function’s parameters, followed by the function’s body. Here’s a basic example:

<?php 

$add = function($x, $y) {
    return $x + $y;
};

In this example, we have created an anonymous function that takes two parameters, $x and $y, and returns their sum. The anonymous function is then assigned to the variable $add. Developers often substitute anonymous functions for named functions, as they provide several benefits.

Advantages of Anonymous Functions

One of the main advantages of anonymous functions is that they are very convenient for creating small, one-time use functions. For example, suppose you want to sort an array of strings based on the length of each string. You can do this using the usort function and an anonymous function:

<?php 

$strings = ['apple', 'banana', 'orange', 'pear'];

usort($strings, function($a, $b) {
    return strlen($a) - strlen($b);
});

print_r($strings);

In this example, we have used an anonymous function as the second parameter to usort. The anonymous function takes two parameters, $a and $b, which are two elements of the $strings array. The anonymous function returns the difference between the lengths of $a and $b, which is used by usort to determine the order of the elements.

Another advantage of anonymous functions is that they can capture variables from their parent scope. This allows you to create functions that can access variables outside of their own scope. For example:

<?php 

function create_multiplier($x) {
    return function($y) use ($x) {
        return $x * $y;
    };
}

$double = create_multiplier(2);
$triple = create_multiplier(3);

echo $double(5); // Output: 10
echo $triple(5); // Output: 15

In this example, we have created a function called create_multiplier that returns an anonymous function. The anonymous function takes a single parameter, $y, and multiplies it by the value of $x, which was captured from the parent scope using the use keyword. We then create two functions, $double and $triple, by calling create_multiplier with the values 2 and 3, respectively.

Finally, we call $double(5) and $triple(5) to demonstrate how these functions work.

Using Anonymous Functions with Arrays

Developers commonly use anonymous functions with arrays in PHP. For example, the array_map function can be used with an anonymous function to apply a function to each element of an array. Here’s an example:

<?php 

$numbers = [1, 2, 3, 4, 5];

$squared_numbers = array_map(function($x) {
    return $x * $x;
}, $numbers);

print_r($squared_numbers);

In this example, we have used array_map with an anonymous function to create a new array, $squared_numbers, that contains the square of each element in the original array, $numbers.

Anonymous functions can also be used with the array_filter function to filter an array based on a condition. Here’s an example:

<?php 
$numbers = [1, 2, 3, 4, 5];

$even_numbers = array_filter($numbers, function($x) {
    return $x % 2 == 0;
});

print_r($even_numbers);

In this example, we have used array_filter with an anonymous function to create a new array, $even_numbers, that contains only the even numbers from the original array, $numbers.

Anonymous functions can also be used with the array_reduce function to reduce an array to a single value. Here’s an example:

<?php 

$numbers = [1, 2, 3, 4, 5];

$sum = array_reduce($numbers, function($acc, $x) {
    return $acc + $x;
}, 0);

echo $sum; // Output: 15

In this example, we have used array_reduce with an anonymous function to calculate the sum of the elements in the original array, $numbers.

Using Anonymous Functions with Callbacks

Another common use of anonymous functions in PHP is with callbacks. Developers commonly use anonymous functions as callbacks, passing them as arguments to other functions. For example:

<?php 
 
function process_data($data, $callback) {
    // Process data...
    $result = $callback($data);
    // Return result...
    return $result;
}

$data = ['apple', 'banana', 'orange', 'pear'];

$result = process_data($data, function($data) {
    return array_map('strtoupper', $data);
});

print_r($result);

In this example, we have created a function called process_data that takes two parameters: $data and $callback. The function processes the data, then calls the callback with the processed data as an argument, and returns the result. We then call process_data with an array of strings, $data, and an anonymous function that uses array_map to convert the strings to uppercase. The result is an array of uppercase strings.

Usage of PHP Anonymous Functions with Variable Scope

An anonymous function can access variables defined in the parent scope, but only if they are within the same function or method as the anonymous function. Developers refer to this as a closure.

Here’s an example:

<?php 

function outer_function() {
    $x = 1;

    $inner_function = function() use ($x) {
        echo $x;
    };

    $inner_function();
}

outer_function(); // Output: 1

In this example, we have a function called outer_function that defines a variable $x and then defines an anonymous function, $inner_function, that uses $x through the use keyword. The anonymous function is then called within outer_function, and it outputs the value of $x.

However, if we define an anonymous function outside of the parent function or method, it will not have access to variables in the parent scope, unless we use the use keyword to explicitly bring those variables into the anonymous function’s scope. Here’s an example:

<?php 

function outer_function() {
    $x = 1;

    $inner_function = function() use ($x) {
        echo $x;
    };

    $inner_function();
}

outer_function(); // Output: 1

Keep in mind that you can use the reference operator to modify variables in the parent scope with anonymous functions. Here’s an example:

<?php 

function outer_function() {
    $x = 1;

    $inner_function = function() use (&$x) {
        $x = 2;
    };

    $inner_function();

    echo $x; // Output: 2
}

outer_function();

In this example, we have defined an anonymous function that modifies the value of $x using the reference operator &. When the anonymous function is called within outer_function, it modifies the value of $x from 1 to 2. When outer_function continues executing, it outputs the value of $x, which is now 2.

Using Closures with Classes

Another common use of anonymous functions in PHP is with classes. Developers can use anonymous functions to define methods on the fly, eliminating the need to define a separate named method. Here’s an example:

<?php 

class Calculator {
    public $x;
    public $y;

    public function __construct($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    public function calculate($operation) {
        $operations = [
            'add' => function() {
                return $this->x + $this->y;
            },
            'subtract' => function() {
                return $this->x - $this->y;
            },
            'multiply' => function() {
                return $this->x * $this->y;
            },
            'divide' => function() {
                return $this->x / $this->y;
            },
        ];

        if (isset($operations[$operation])) {
            $result = $operations[$operation]();
            return $result;
        } else {
            return null;
        }
    }
}

$calculator = new Calculator(4, 2);

echo $calculator->calculate('add'); // Output: 6
echo $calculator->calculate('subtract'); // Output: 2
echo $calculator->calculate('multiply'); // Output: 8
echo $calculator->calculate('divide'); // Output: 2

In this example, we have defined a class called Calculator that takes two parameters, $x and $y, in its constructor. The class also has a method called calculate that takes a string parameter, $operation, and uses an anonymous function to perform the calculation based on the operation. The anonymous functions are defined in an array called $operations.

When we create a new instance of the Calculator class with values of 4 and 2, we can call the calculate method with different operations and get the corresponding results.

Wrapping Up

In conclusion, anonymous functions are a powerful feature of PHP. That allow developers to create functions without giving them a specific name.

Anonymous functions are very convenient for creating small, one-time use functions. And they have a number of advantages over named functions, such as the ability to capture variables from their parent scope.

Developers commonly use anonymous functions with arrays and callbacks in PHP. Additionally, anonymous functions have a variety of other use cases. If you’re not already using anonymous functions in your PHP development, you should definitely consider adding them to your toolbox.