Sling Academy
Home/PHP/Using Anonymous Functions in PHP

Using Anonymous Functions in PHP

Last updated: January 09, 2024

Introduction

Anonymous functions, also known as closures, are functions without a specified name. They are capable of faster and more dynamic programming in PHP, especially valuable for callbacks and event-driven code.

Basic Usage of Anonymous Functions

An anonymous function is defined using the function keyword, followed by the parenthesis without a name:

$greet = function($name) {
    echo "Hello, {$name}!";
};
$greet("World");

This code defines a function that greets a user and assigns it to the variable $greet. To invoke the function, you simply use the variable as a function call.

Passing Variables to the Use Clause

An anonymous function can inherit variables from the parent scope using the use keyword:

$greeting = 'Hello';
$greet = function($name) use ($greeting) {
    echo "{$greeting}, {$name}!";
};
$greet("World");

Here, $greeting is passed to the closure using the use clause, making it available within the function.

Anonymous Functions as Callbacks

Anonymous functions shine as callbacks in functions like array_map:

$numbers = [1, 2, 3, 4];
$doubled = array_map(function($number) {
    return $number * 2;
}, $numbers);
print_r($doubled);

The above code snippet applies an anonymous function to each element of the $numbers array, returning an array of doubled values.

Returning Anonymous Functions

Anonymous functions can be used to create factory functions which return other functions:

function multiplier($factor) {
    return function($num) use ($factor) {
        return $num * $factor;
    };
}
$double = multiplier(2);
echo $double(5); // Outputs: 10

A multiplier function returns another function that multiplies a number by a given factor, in this case, doubling the input.

Advanced Use in Objects

In an object context, anonymous functions can be used as methods or can be bound to objects:

class Greeter {
    public $greeting = 'Hello';
}

$greeter = new Greeter();
$helloWorld = function($name) {
    echo "{$this->greeting}, {$name}!";
};

$boundHelloWorld = $helloWorld->bindTo($greeter, 'Greeter');
$boundHelloWorld("World");

In this example, $helloWorld is an anonymous function that uses $this, which is not defined until it is bound to an object of the class Greeter.

Manipulating Arrays with Array Functions

Combining array functions with anonymous functions allows for powerful array manipulation:

$students = [
    ['name' => 'Alice', 'score' => 9.8],
    ['name' => 'Bob', 'score' => 7.3],
    ['name' => 'Charlie', 'score' => 6.9],
];
usort($students, function($a, $b) {
    return $a['score'] <$ b['score'];
});
print_r($students);

The given code sorts the array $students by their score attribute using the usort function and an appropriate comparison anonymous function.

Using Anonymous Functions with PHP Built-in Interfaces

An anonymous function can be converted to an instance of Closure class which is a built-in interface for callable functions in PHP:

$adder = function($x, $y) {
    return $x + $y;
};
$addition = $adder(1, 2);
echo $addition; // Outputs: 3

This feature allows anonymous functions to be passed where instances of Closure or callables are required.

Anonymous Functions with Generators

Anonymous functions can be used along with generators to handle data iteration:

$fibonacci = function($count) {
    $first = 0;
    $second = 1;
    for($i = 0; $i < $count; $i++) {
        yield $first;
        $next = $first + $second;
        $first = $second;
        $second = $next;
    }
};
foreach($fibonacci(10) as $num) {
    echo $num . ' ';
}

This generator produces the first ten numbers of the Fibonacci sequence.

Conclusion

Anonymous functions in PHP provide flexibility and a concise syntax for various scenarios like event handling, array manipulation, and callback design. As you embrace anonymous functions, you’ll find yourself writing more readable and maintainable PHP code.

Next Article: Using ‘declare’ construct in PHP

Previous Article: PHP: Define function that returns multiple values (3 ways)

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array