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

History of PHP: From PHP/FI to Modern Web Development

You use PHP every day if you build websites, but most people do not know where it came from or…

PHP array_merge_recursive: Merge Arrays Deeply

PHP array_merge_recursive joins two or more arrays into one nested array and keeps all values with their keys. Syntax of…

PHP cURL: HTTP Requests and Responses in PHP

In PHP, there are plenty of times when you need to connect with other servers or APIs. That's where the…

PHP $_GET: How to Create Dynamic URLs in PHP?

The PHP $_GET— is a tiny part, but strong in the data processing using the URL. There is a site that…

PHP fwrite: How to Write Data to Files in PHP

actions, store settings, or even create log files for debugging. That’s where PHP fwrite comes in. It writes data to…

Parameters and Arguments in PHP: What’s the Difference?

If you're coding in PHP you've most probably come across the terms 'parameters' and 'arguments' in functions. Well, they are…

PHP File Inclusion: require, include, require_once, include_once

PHP offers four main functions to include files: require, require_once, include, and include_once. Each one gives you a similar purpose…

PHP Variadic Functions: Use Unlimited Arguments

PHP Variadic functions show you a way to handle a variable number of arguments within a function. They are designed…

PHP range Function: Create Arrays with Sequence Values

The PHP range function helps you make sequences. Without it, you would write loops every time you need numbers or…

PHP Strings: Types, Variables & Syntax Tips

If you start working with PHP, it won't take you that long to figure out that strings are everywhere. Besides…

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.