Closure
The class of anonymous functions and closures.
Syntax
$closure = function () { … }Return value
ClosureAn object that can be called like a function.
Examples
A closure is an object of the Closure class:
<?php
$double = fn (int $n) => $n * 2;
var_dump($double instanceof Closure);
echo $double(21);Output:
bool(true)
42The call() method runs the function inside an object:
<?php
class Counter
{
private int $count = 5;
}
$peek = fn () => $this->count;
echo $peek->call(new Counter());Output:
5A function as a value:
<?php
$upper = strtoupper(...);
echo $upper('php'), ' ', get_class($upper);Output:
PHP ClosureNotes
Function parameters can be typed Closure — it is stricter than callable and rejects strings with function names.
See also
- call_user_func — Calls a function held in a variable.
- is_callable — Checks whether a value can be called as a function.
- array_map — Applies a function to every element of an array.
Related recipes
In the tutorial
- Anonymous functions and closures — Functions as values in PHP — anonymous and arrow functions, the use construct, the callable type.