Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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)
42

The 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:

5

A function as a value:

<?php
 
$upper = strtoupper(...);
 
echo $upper('php'), ' ', get_class($upper);

Output:

PHP Closure

Notes

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

Thanks for reading!

Donate to the site — we work hard for you.