PHP Anonymous Functions
In this page:
$closure = function ($parameter) use ($outer_variable) {
return $parameter;
};
$closure($argument);
What is an Anonymous Function?
An anonymous function (a closure) is defined without ever being given a name of its own — instead of calling it by name later, you typically assign it directly to a variable or hand it straight to another function as an argument.
Example: What is an Anonymous Function?
<?php
$greet = function ($name) {
// Print "Hello, $name!" to the output
echo "Hello, $name!";
};
$greet("Alice");
?>
Login to try C/C++/Java/PHP code in the editor
Using Closures as Callbacks
Built-in array functions like array_filter() and usort() expect a callback to tell them exactly how to filter or compare elements.
An anonymous function defined right at the call site is a natural fit here, since that logic is usually one-off and doesn't need a name of its own elsewhere in the codebase.
Example: Using Closures as Callbacks
<?php
// Declare `$numbers` as an array: `[1, 2, 3, 4, 5]`
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, function ($n) {
// Return `$n % 2 === 0` from this function
return $n % 2 === 0;
});
// Print a human-readable dump of `$even`
print_r($even);
?>
Login to try C/C++/Java/PHP code in the editor
The 'use' Keyword
The use keyword lets a closure pull in variables from the scope it was defined in — without it, the closure has no access to anything outside its own parameter list, even variables that were clearly visible right where the closure was written.
Example: The 'use' Keyword
<?php
// Declare `$tax`, set to `0.1`
$tax = 0.1;
$addTax = function ($price) use ($tax) {
// Return `$price + ($price * $tax)` from this function
return $price + ($price * $tax);
};
// Print `$addTax(100)` to the output
echo $addTax(100);
?>
Login to try C/C++/Java/PHP code in the editor
Type Hinting Callables
Declaring a parameter's type as callable (or specifically Closure) documents that a function expects to receive something it can invoke, and lets PHP enforce that at the call site rather than only discovering the mistake when the function tries to call a non-callable value.
Example: Type Hinting Callables
<?php
// Define the function `apply` taking `callable $fn`, `$value`
function apply(callable $fn, $value) {
// Return `$fn($value)` from this function
return $fn($value);
}
// Print `apply(function ($x) { return $x * 2; }, 5)` to the output
echo apply(function ($x) { return $x * 2; }, 5);
?>
Login to try C/C++/Java/PHP code in the editor
Closures and $this
A closure defined inside a class method automatically has access to $this, referring to the same object instance the enclosing method belongs to — letting the closure read or modify that object's properties and call its other methods just as the surrounding method could.
Example: Closures and $this
<?php
// Define the class `Counter`
class Counter {
// Declare the private property `$count`, set to `0`
private $count = 0;
// Define the function `makeIncrementer` with no parameters
function makeIncrementer() {
// Return `function () {` from this function
return function () {
$this->count++;
// Return `$this->count` from this function
return $this->count;
};
}
}
// Create a new `Counter` instance, stored in `$counter`
$counter = new Counter();
// Declare `$increment`, set to `$counter->makeIncrementer()`
$increment = $counter->makeIncrementer();
// Print `$increment()` to the output
echo $increment();
?>
Login to try C/C++/Java/PHP code in the editor
- Expecting a closure to see outer variables automatically, when they must be imported with
use ($var). - Expecting
use ($count)to update the outer variable, when it captures a copy; useuse (&$count)for a reference. - Forgetting the semicolon after an anonymous function assigned to a variable, which causes a parse error.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: