Anonymous Functions

Ma Mahalakshmi V Updated 14 Nov 2026
8 min read ·Lesson 74 of 256

What Is an Anonymous Function?

In simple terms: An anonymous function is a function without a name. Instead of declaring it once and calling it by name, you create it as a value — store it in a variable or pass it directly to another function.

Technically: An anonymous function is created with the function keyword in an expression context. The result is an object of the built-in Closure class, which can be called like a function, passed as an argument, returned from functions, and stored in arrays. Anonymous functions can capture variables from the surrounding scope with a use clause.

$greet = function (string $name): string {
    return "Hello, $name!";
};

Why Anonymous Functions Exist

Many PHP functions accept a callback — a function that tells them how to do part of their work:

  • array_map() — how to transform each element
  • array_filter() — which elements to keep
  • usort() — how to compare two elements
  • Event handlers, route handlers, and middleware in frameworks

Declaring a separate named function for every small callback would clutter the code. An anonymous function can be written exactly where it is needed.


Syntax

$variable = function (parameters) use (captured variables): ReturnType {
    // body
};

Note: When an anonymous function is assigned to a variable, the statement ends with a semicolon after the closing brace — it is an assignment, not a function declaration.

Example

<?php
$greet = function (string $name): string {
    return "Hello, $name!";
};

echo $greet('Asha') . "\n";
echo $greet('Bala') . "\n";

var_dump($greet instanceof Closure);

Output

Hello, Asha!
Hello, Bala!
bool(true)

How It Works

  1. The function (...) { ... } expression creates a Closure object.
  2. The object is stored in $greet.
  3. $greet('Asha') calls it, just like a named function.
  4. instanceof Closure confirms that anonymous functions are objects.

Anonymous Functions as Callbacks

The most common use is passing an anonymous function directly to another function.

Transforming With array_map()

<?php
$prices = [100, 250, 499];

$withGst = array_map(function (float $price): float {
    return round($price * 1.18, 2);
}, $prices);

print_r($withGst);

Output

Array
(
    [0] => 118
    [1] => 295
    [2] => 588.82
)

array_map() calls the anonymous function once for each price and collects the results in a new array.

Filtering With array_filter()

<?php
$orders = [
    ['id' => 1, 'total' => 450, 'paid' => true],
    ['id' => 2, 'total' => 1800, 'paid' => false],
    ['id' => 3, 'total' => 2400, 'paid' => true],
];

$largePaidOrders = array_filter($orders, function (array $order): bool {
    return $order['paid'] && $order['total'] >= 1000;
});

foreach ($largePaidOrders as $order) {
    echo "Order {$order['id']}: ₹{$order['total']}\n";
}

Output

Order 3: ₹2400

The callback returns true for elements to keep. array_filter() preserves the original keys.

Sorting With usort()

<?php
$students = [
    ['name' => 'Kavin', 'score' => 82],
    ['name' => 'Anu', 'score' => 95],
    ['name' => 'Bala', 'score' => 82],
];

usort($students, function (array $a, array $b): int {
    return [$b['score'], $a['name']] <=> [$a['score'], $b['name']];
});

foreach ($students as $student) {
    echo "{$student['name']}: {$student['score']}\n";
}

Output

Anu: 95
Bala: 82
Kavin: 82

The comparison sorts by score (descending), then by name (ascending) for equal scores. See Spaceship Operator.


Capturing Variables With use

An anonymous function has its own scope, like any function. It cannot see variables from the surrounding code unless you import them with use.

Without use

<?php
$taxRate = 18;

$addTax = function (float $amount): float {
    return $amount * (1 + $taxRate / 100);   // $taxRate is undefined here
};

echo $addTax(100);

Output

PHP Warning:  Undefined variable $taxRate in /path/script.php on line 5
100

Inside the function, $taxRate does not exist, so PHP treats it as null (with a warning), and the tax becomes zero.

With use

<?php
$taxRate = 18;

$addTax = function (float $amount) use ($taxRate): float {
    return $amount * (1 + $taxRate / 100);
};

echo $addTax(100) . "\n";

Output

118

use ($taxRate) copies the variable into the anonymous function. A function that captures variables from its surroundings is called a closure; closures are covered in more depth in Closures.

use Captures the Value at Creation Time

<?php
$taxRate = 18;

$addTax = function (float $amount) use ($taxRate): float {
    return $amount * (1 + $taxRate / 100);
};

$taxRate = 28;   // changed after the closure was created

echo $addTax(100) . "\n";

Output

118

The closure still uses 18, because use copied the value when the function was created. Later changes to $taxRate do not affect it.

Capturing by Reference: use (&$variable)

To share a variable with the closure (so changes go both ways), capture it by reference:

<?php
$count = 0;

$increment = function () use (&$count): void {
    $count++;
};

$increment();
$increment();
$increment();

echo "Count: $count\n";

Output

Count: 3

With &, the closure works on the original $count. Use this sparingly — returning values is usually clearer.


Anonymous Functions vs Arrow Functions

PHP 7.4 introduced arrow functions, a shorter syntax for anonymous functions that contain a single expression:

<?php
$taxRate = 18;

$addTax1 = function (float $amount) use ($taxRate): float {
    return $amount * (1 + $taxRate / 100);
};

$addTax2 = fn(float $amount): float => $amount * (1 + $taxRate / 100);

echo $addTax1(100) . "\n";
echo $addTax2(100) . "\n";

Output

118
118
Anonymous FunctionArrow Function
Syntaxfunction (...) use (...) { ... }fn(...) => expression
BodyAny number of statementsA single expression
Capturing outer variablesExplicit, with useAutomatic, by value
Capturing by referencePossible with use (&$x)Not possible

Use arrow functions for short callbacks and anonymous functions when the body needs several statements. See Arrow Functions.


Recursive Anonymous Functions

An anonymous function has no name to call itself with. To make it recursive, capture the variable that holds it by reference:

<?php
$factorial = function (int $n) use (&$factorial): int {
    return $n <= 1 ? 1 : $n * $factorial($n - 1);
};

echo $factorial(5) . "\n";

Output

120

The reference is needed because $factorial is assigned only after the function is created; capturing by value would capture null. For most recursion, a named function is simpler.


Immediately Invoked Function Expressions

An anonymous function can be created and called at once. This is sometimes used to compute a value with temporary variables that should not leak into the surrounding scope:

<?php
$config = (function (): array {
    $environment = 'production';
    $isProduction = $environment === 'production';

    return [
        'debug' => !$isProduction,
        'cache' => $isProduction,
    ];
})();

var_dump($config['debug'], $config['cache']);
var_dump(isset($environment));

Output

bool(false)
bool(true)
bool(false)

$environment and $isProduction exist only inside the function, so they do not pollute the outer scope. Configuration files in some frameworks use a similar pattern.


Static Anonymous Functions

Inside a class, an anonymous function automatically has access to $this. Declaring it static prevents this binding:

$formatter = static function (float $amount): string {
    return '₹' . number_format($amount, 2);
};

A static closure cannot use $this, which avoids accidentally keeping the surrounding object alive in memory and makes the function's independence explicit. This matters mainly in object-oriented code (see Closures).


Practical Example: A Product Filter

<?php
$products = [
    ['name' => 'Desk Lamp', 'category' => 'Home', 'price' => 1299],
    ['name' => 'Notebook', 'category' => 'Stationery', 'price' => 60],
    ['name' => 'Wall Clock', 'category' => 'Home', 'price' => 899],
    ['name' => 'Gel Pen', 'category' => 'Stationery', 'price' => 25],
    ['name' => 'Cushion', 'category' => 'Home', 'price' => 499],
];

// Values that would normally come from the user's filter form
$category = 'Home';
$maxPrice = 1000;

$matches = array_filter($products, function (array $product) use ($category, $maxPrice): bool {
    return $product['category'] === $category && $product['price'] <= $maxPrice;
});

usort($matches, function (array $a, array $b): int {
    return $a['price'] <=> $b['price'];
});

$labels = array_map(function (array $product): string {
    return $product['name'] . ' — ₹' . number_format($product['price']);
}, $matches);

echo implode("\n", $labels) . "\n";

Output

Cushion — ₹499
Wall Clock — ₹899

Step-by-Step Explanation

  1. Filter: the first anonymous function captures $category and $maxPrice with use and keeps only matching products. The Desk Lamp is excluded because it costs more than ₹1000.
  2. Sort: the second function orders the matches by price; usort() also re-indexes the array.
  3. Map: the third function turns each product into a display label.
  4. Each step is a small, focused function written exactly where it is used.

Common Mistakes

Forgetting the Semicolon After an Assigned Function

$fn = function () {
    return 1;
}          // parse error: missing ;

Fix: End the assignment with };.

Forgetting use

Effect: "Undefined variable" warnings and wrong results inside the function.

Fix: Import needed variables with use, or use an arrow function.

Expecting use to See Later Changes

Effect: The closure keeps the value from when it was created.

Fix: Pass the value as an argument, or capture by reference if sharing is truly intended.

Writing Long Logic Inline

Effect: Large anonymous functions inside array_map() or usort() calls are hard to read and impossible to reuse.

Fix: Move long logic into a named function or method, and pass that instead.


Best Practices

  • Use anonymous functions for short callbacks that are used in one place.
  • Import only the variables the function needs, by value.
  • Use arrow functions for single-expression callbacks.
  • Declare parameter and return types on anonymous functions as well.
  • Use static closures in classes when $this is not needed.

Official reference: https://www.php.net/manual/en/functions.anonymous.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about Anonymous Functions and get answers drawn from it.

Signed-in readers only.