PHP Anonymous Function: How It Works with Examples

php anonymous functions

The anonymous function in PHP lets you define a small task that doesn’t require a function name.

Understand the Anonymous Function in PHP

You can use it like any other function, store it in a variable, or pass it as an argument. This feature was added in PHP 5.3.

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

Here is an example:

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

This will show you the following output:

Hello, FlatCoding Students

You can assign the function to the following:

  • A variable
  • Store it in an array
  • Pass it as an argument.

Anonymous functions can also capture variables from the parent scope with the use keyword.

For example:

$message = "Hello";

$greet = function() use ($message) {
    echo $message;
};

$greet();

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

  • Makes the code shorter
  • Keeps small tasks in one place
  • Works with functional style code

How to Pass Anonymous Functions as Arguments

You can pass the anonymous function as an argument for built-in functions in PHP.

For example:

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

print_r($doubled);

The output:

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

Here is another example with usort:

$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

PHP allows you to write a function that creates and returns another function. You can use this pattern to make factories or change logic.

Here is an example:

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

It sets a function that returns an anonymous function. The inner function takes a value from the outer function to multiply its input.

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 takes a parameter from the first function, and the inner one adds that parameter to a name.

Instantly Invoked Function Expressions (IIFE)

An IIFE runs right after you create it. PHP uses wrapping parentheses to make this work

Here is an example:

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

This runs an anonymous function immediately without inputs. It calculates five squared inside the function.

For another example:

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

The output:

Welcome, Charlie

This defines and runs an anonymous function directly. It takes a name as input and builds a welcome message.

Add Anonymous Functions to Classes

You can store anonymous functions as properties in classes. Here is an example:

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 assigns an anonymous function to a property in its constructor. The function prints a log message with a prefix. It shows how to call the function with the property’s __invoke method.

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 holding an anonymous function that adds two numbers. You run the function by calling __invoke with two arguments.

Understand the Closures in PHP

A closure is an anonymous function implemented with 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 output:

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

This remembers and updates $count between calls.

Shorthand of Anonymous Function in PHP

PHP supports a short syntax for anonymous functions called arrow functions.

Here is the syntax:

$add = fn($a, $b) => $a + $b;

echo $add(5, 3); // 8

Here are the differences between anonymous functions and arrow functions:

Anonymous functions use the use keyword for external variables, while the arrow functions automatically capture them.

The arrow functions inherit the parent scope by default. Anonymous functions need to use import variables.

Here is a table that shows you the 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 function stores in a variable for later use and takes a number and multiplies it by itself.

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 a 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!"); 

This function takes a string that uses substr to split 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

You learned what anonymous functions are and how to use them in PHP.

Here is a quick recap:

  • PHP supports these features since version 5.3 for anonymous functions and version 7.4 for arrow functions.
  • PHP uses the Closure class behind every anonymous function, and many of these functions 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?

An anonymous function is a function defined without a name. It can be assigned to a variable or passed directly as an argument. In PHP, you can write:

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

How do you declare and use an anonymous function in PHP?

You declare it using the function keyword and assign it to a variable. Example:

$sum = function($a, $b) { return $a + $b; }; 
echo $sum(5, 3);
You can also pass it as a callback in array functions.

What is the difference between anonymous functions and arrow functions in PHP?

Arrow functions use the fn keyword and automatically capture variables from the parent scope. They are limited to a single expression. Example:

$factor = 2; 
$multiply = fn($x) => $x * $factor; 
echo $multiply(5); 

What are common use cases for anonymous functions?

Common uses include:
  • Callbacks in array_map, usort, and events
  • Creating isolated scope with IIFEs
  • Small inline logic without naming clutter
Example:
$numbers = [1, 2, 3, 4]; 
$even = array_filter($numbers, fn($n) => $n % 2 === 0); 
print_r($even); 

Similar Reads

How to Remove the Last Character from a String in PHP

You may need to cut the last character from a string if it shows by mistake in PHP. That may…

PHP Singleton Pattern: How to Use with Examples

The PHP singleton design pattern makes sure that the class has only one instance and provides a global access point…

PHP Arrow Functions: Understanding “fn” Syntax

Arrow functions were introduced in PHP 7.4. They offer you a way to write simple operations, such as calculations, filters,…

Class and Object in PHP: How They Work with a Real Example

Classes and objects are important parts of OOP in PHP. They help you organize your code so you can update…

PHP Variable Scope: Local, Global & Static

The variable scope in PHP refers to the variables, functions, and classes that can be accessed within different parts of…

PHP Associative Array: Optimal Data Organization

The PHP associative array is a structured collection wherein data elements are organized into lists or groups. Each element is…

PHP trim(): How to remove Whitespace from String

Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…

Traits in PHP: What They Are & Examples

PHP introduced traits to solve a problem with code reuse. Before traits, developers used inheritance and interfaces to share functionality…

Understanding the PHP Enumerable

Actually, the PHP enumerable is a new feature of 8.1 which allows you to define a new type. This feature…

Understanding the Increment and decrement operators in PHP

The increment and decrement are operators that can be used to increase or decrease the variable values which have a…

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.