Anonymous Functions and Closures
Write inline functions and capture variables with use.
Anonymous Functions and Closures is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Are Anonymous Functions?
An anonymous function (lambda) is a function without a name. In PHP it's an instance of the built-in Closure class and can be stored in a variable, passed as an argument, or returned from another function.
Basic Anonymous Function
Assign a function to a variable and call it:
<?php
$double = function(int $n): int {
return $n * 2;
};
echo $double(5); // 10
echo $double(21); // 42Passing Anonymous Functions
Pass a closure as an argument to functions like array_map, usort, or your own callbacks:
<?php
$nums = [3, 1, 4, 1, 5, 9];
$squared = array_map(function(int $n): int {
return $n ** 2;
}, $nums);
print_r($squared); // [9, 1, 16, 1, 25, 81]Returning Functions
A function can create and return a closure — this is a factory pattern:
<?php
function makeMultiplier(int $factor): Closure {
return function(int $n) use ($factor): int {
return $n * $factor;
};
}
$triple = makeMultiplier(3);
$tenX = makeMultiplier(10);
echo $triple(5); // 15
echo $tenX(5); // 50Closures and use
Closures can capture variables from the outer scope with use. Capture is by value (copy) unless you add &:
<?php
$taxRate = 0.18;
$addTax = function(float $price) use ($taxRate): float {
return $price * (1 + $taxRate);
};
$taxRate = 0.20; // change outer variable
echo $addTax(100); // 118 — captured value at creation timeCapture by Reference with use(&)
To let the closure see updated outer values, capture by reference:
<?php
$count = 0;
$increment = function() use (&$count): void {
$count++;
};
$increment();
$increment();
echo $count; // 2Arrow Functions (PHP 7.4)
Arrow functions are compact single-expression closures that auto-capture outer scope by value:
<?php
$rate = 1.18;
$prices = [10, 20, 30];
// Arrow function — no 'use' needed
$withTax = array_map(fn($p) => $p * $rate, $prices);
print_r($withTax); // [11.8, 23.6, 35.4]Arrow Functions Cannot Mutate Outer Scope
Arrow functions capture by value only — they cannot modify outer variables:
<?php
$total = 0;
$nums = [1, 2, 3];
// This does NOT modify $total!
array_walk($nums, fn($n) => $total += $n);
echo $total; // 0
// Use a reference closure for mutation:
array_walk($nums, function($n) use (&$total) { $total += $n; });
echo $total; // 6Closures as Callbacks
Many PHP functions accept a callable — you can pass a closure, an array [$obj, 'method'], or a string function name:
<?php
$words = ['banana', 'apple', 'cherry'];
usort($words, fn($a, $b) => strcmp($a, $b));
print_r($words); // ['apple', 'banana', 'cherry']Immediately Invoked Closure
You can define and call a closure on the same line — useful to create an isolated scope:
<?php
$result = (function(): int {
$x = 10;
$y = 20;
return $x + $y;
})();
echo $result; // 30
// $x and $y are not in outer scopeClosure::bind and bindTo
You can rebind a closure to a different object's context using Closure::bind():
<?php
class Counter {
private int $value = 0;
}
$increment = Closure::bind(function(int $by): void {
$this->value += $by;
}, new Counter(), Counter::class);
// Now $increment has access to private $valueQuick Check
Which of the following is the main difference between a regular closure with use and an arrow function in PHP?
Recap: Anonymous Functions and Closures
Summary:
- Anonymous functions are stored in variables and passed around
- Closures capture outer variables with
use($var)(by value) oruse(&$var)(by reference) - Arrow functions (PHP 7.4) auto-capture outer scope by value
- Useful for callbacks: array_map, usort, array_filter…
- Can be returned from factory functions
Frequently asked questions
Is the “Anonymous Functions and Closures” lesson free?
Yes — the full text of “Anonymous Functions and Closures” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Anonymous Functions and Closures”?
Write inline functions and capture variables with use. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Anonymous Functions and Closures” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Defining and Calling Functions
- Default and Variadic Parameters
- Variable Scope: Local and Global
- Anonymous Functions and Closures