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

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 array_intersect_key Function: How it Works with Examples

The array_intersect_key in PHP compares arrays by keys and returns only the parts that match. It is useful when you…

PHP array_fill_keys: Create Arrays with Specific Keys

The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…

PHP XML Parsers: Everything You Need to Know

In PHP, manipulation of XML data can be very critical when most systems' data exchange relies on the format. XML—Extensible…

PHP file_exists: Check File and Directory Existence

Whether you are just trying to keep your app from crashing or making sure your users’ uploads don’t accidentally overwrite…

PHP $_COOKIE: Securely Store and Manage Data

Ever notice how some websites just seem to "know" you? That’s thanks to cookies! When you’re working with PHP, $_COOKIE becomes a…

PHP Predefined Constants Explained Simply

PHP has a number of predefined constants that give you some information about the language and its environment. You can…

MongoDB PHP Driver: Install and Get Started

Traditional relational databases like MySQL often take center stage. However, with the rise of NoSQL databases, MongoDB has emerged as…

PHP fclose(): Close Access of File Manipulation

Actually, PHP has a built-in function that doesn’t get the spotlight—fclose(). It ends the file manipulation code. Let’s break down…

PHP str_replace Function: How it Works with Examples

If you find a word that does not fit and want to fix it. You can use the PHP str_replace…

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.