How PHP Anonymous Functions and Closures Work

php anonymous functions

Anonymous functions in PHP help avoid writing named functions for small tasks. They let you define functions in place to improve code readability. This feature first appeared to simplify callbacks and reduce clutter in codebases.

Understand the Anonymous Function In PHP

An anonymous function in PHP is a function with no name. It behaves like a normal function, but you can store it in a variable or pass it around. PHP introduced this feature in version 5.3.

You can declare an anonymous function with the function keyword without a name. You store it in a variable for later use.

$greet = function($name) {
    return "Hello, " . $name;
};
echo $greet("Alice");

Here is the output:

Hello, Alice

You can assign the function to a variable, store it in an array, or pass it as an argument. Anonymous functions can also capture variables from the parent scope with the use keyword.

You may need to use an anonymous function for the following reasons:

  • Simplify callbacks
  • Reduce boilerplate code
  • Encapsulate short logic
  • Improve readability
  • Support functional programming

How to Pass Anonymous Functions as Arguments

PHP’s array functions accept callbacks. Anonymous functions help define this logic inline.

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

print_r($doubled);

Output:

Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
)

You can define a sort rule with usort function.

$names = ["John", "Alex", "Zoe"];
usort($names, function($a, $b) {
    return strlen($a) - strlen($b);
});

print_r($names);

Output:

Array
(
[0] => Zoe
[1] => John
[2] => Alex
)

Return Anonymous Functions

You can write a function that creates and returns another function. This enables dynamic behavior and partial application.

You can use this pattern to build factories or customize logic.

For example:

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

It defines a function that returns an anonymous function. The inner function uses a value from the outer function to multiply its input. It shows how to create customized functions with captured variables.

Here is another example:

function greeter($param) {
    return function($name) use ($param) {
        return $param. ', ' . $name;
    };
}
$sayHello = greeter('Hello');
echo $sayHello('Bob');

The output:

Hello, Bob

This function returns another function that uses a param from the first function. The inner function joins the param with a name. It shows how to create personalized messages with captured values.

Instantly Invoked Function Expressions (IIFE)

An IIFE runs as soon as you define it. PHP supports this with the wrapping parentheses.

For example:

$result = (function() {
    return 5 * 5;
})();
echo $result; // 25

This code runs an anonymous function right away without inputs. It calculates the square of five inside the function. It saves the result in a variable for further use.

Here is another example:

$message = (function($name) {
    return "Welcome, " . $name;
})("Charlie");
echo $message;

The output:

Welcome, Charlie

This code defines and runs an anonymous function immediately. It takes a name as input and creates a welcome message. It stores the message in a variable for later use.

Add Anonymous Functions to Classes

You can store anonymous functions as properties in classes. This supports dynamic behaviors.

For example, you can create a class that holds an add function property:

class Logger {
    public $log;
    public function __construct() {
        $this->log = function($msg) {
            echo "[LOG]: " . $msg;
        };
    }
}
$logger = new Logger();
$logger->log->__invoke("System started");

The output:

[LOG]: System started

This class sets a property to an anonymous function inside its constructor. The function prints a log message with a prefix. It shows how to call the function with the __invoke method on the property.

Here is another example:

class Calculator {
    public $operation;
}
$calc = new Calculator();
$calc->operation = function($a, $b) {
    return $a + $b;
};
echo $calc->operation->__invoke(3, 4); // 7

This class has a public property to store a function. The property holds an anonymous function that adds two numbers. You run the function by calling __invoke with two arguments.

What are Closures

A closure is an anonymous function implemented using the closure mechanism that captures variables from its parent scope. It keeps these variables even when the outer function exits.

So, PHP generates an instance of the closure class to represent it when you create a closure. You use the use keyword to import external variables.

Here is an example:

$message = "Hi";
$closure = function($name) use ($message) {
    return $message . ", " . $name;
};
echo $closure("Dana");

The putout:

Hi, Dana

It keeps $message from the outer scope.

Here is another example:

function counter() {
    $count = 0;
    return function() use (&$count) {
        $count++;
        return $count;
    };
}
$increment = counter();
echo $increment(); // 1
echo $increment(); // 2

It remembers and updates $count between calls.

Differences Between Anonymous Functions and Arrow Functions

Anonymous functions use use for external variables. Arrow functions automatically capture them.

while the Arrow functions inherit the parent scope by default. Anonymous functions require use to import variables.

Here is a table that shows you key differences:

FeatureAnonymous FunctionArrow Function
Scope BindingManual with useAutomatic parent scope
Syntaxfunction(...) use (...) { ... }fn(...) => ...
Introduced InPHP 5.3PHP 7.4

PHP Version Compatibility

  • Anonymous functions appeared in PHP 5.3.
  • Closures with use also appeared in PHP 5.3.
  • Closure::fromCallable was added in PHP 7.1.
  • Typed properties and return types appeared in PHP 7.4 and 7.1.

Examples of PHP Anonymous Functions and Closures

Assign an anonymous function to a variable in PHP:

$square = function($n) {
    return $n * $n;
};
echo $square(6); // 36

This code defines an anonymous function with one number input. It multiplies the number by itself. It shows how to store and use a simple calculation in a variable.

Append an exclamation mark in PHP:

$appendExclamation = function($text) {
    return $text . "!";
};
echo $appendExclamation("Wow"); // Wow!

It takes one text input and adds an exclamation mark to the end of the text. It shows a quick way to change text with a function.

Repeat a text in PHP anonymous function:

$repeat = function($text, $times) {
    return str_repeat($text, $times);
};
echo $repeat("Ho ", 3);

The output:

Ho Ho Ho

This code defines an anonymous function with two inputs. It repeats the text the given number of times. It shows how to use str_repeat inside an assigned function.

Remove the last character of a string using an anonymous function:

$removeLastChar = function($text) {
    return substr($text, 0, -1);
};
echo $removeLastChar("Hello!"); 

You will see how this example works. The function takes a string, uses substr to cut off the last character, and returns the shortened string.

Here is the output:

Hello

Chains multiple checks:

$validators = [
    function($v) { return is_numeric($v); },
    function($v) { return $v > 0; }
];
$value = 10;
$valid = array_reduce($validators, function($carry, $fn) use ($value) {
    return $carry && $fn($value);
}, true);
echo $valid ? "Valid" : "Invalid"; // Valid

This code creates two anonymous functions in an array. It checks if a value is numeric and greater than zero. It uses array_reduce to apply all checks and decide if the value passes validation.

Wrapping Up

In this article, you learned what anonymous functions are and how to use them in PHP. You also explored closures, arrow functions, and version compatibility.

Here is a quick recap:

  • PHP supports these features since version 5.3 for anonymous functions and version 7.4 for arrow functions.
  • Behind every anonymous function, PHP uses the Closure class, and many of these functions are implemented to encapsulate logic dynamically.
  • Anonymous functions let you define functions without names.
  • Closures import variables from the outer scope.
  • Arrow functions simplify how scope links to variables.

FAQs

What is an anonymous function in PHP?

An anonymous function is a function with no name that you can store in a variable or pass around.

How do you declare an anonymous function?

Use the function keyword without a name, assign it to a variable.

What is the use of closures in PHP?

Closures capture variables from their parent scope for use later.

How do arrow functions differ from anonymous functions?

Arrow functions inherit the parent scope automatically while anonymous functions need use.

Which PHP version supports anonymous functions?

PHP 5.3 introduced anonymous functions, and PHP 7.4 added arrow functions.

Can you return an anonymous function from another function?

Yes. You can build dynamic factories or partially applied functions.

How do you pass an anonymous function as a callback?

You can pass it directly to array functions, sort functions, or any function expecting a callback.
Previous Article

JavaScript Math log: How it Works with Examples

Next Article

10 Best Programming Languages for Web Development

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.