Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 147 ยท Functions

Anonymous Functions and Closures

Learn PHP anonymous functions and closures - capturing variables with use, by-reference capture, arrow functions fn, callables, and first-class callable syntax strlen(...).

An anonymous function is a function without a name that you create as a value. You can store it in a variable, pass it to another function, return it from a function, or keep it in an array. In PHP, every anonymous function is an object of the built-in class Closure, which is why they're usually just called closures.

Closures are everywhere in modern PHP: sorting with usort, transforming arrays with array_map, defining routes in a framework, registering event listeners, and delaying work until it's needed. This lesson covers the full syntax, how closures capture variables with use, short arrow functions with fn, the different kinds of callables PHP accepts, and the PHP 8.1 first-class callable syntax strlen(...).

You should be comfortable with Variable Scope first: closures are mostly about how they cross scope boundaries.

Functions as values

The syntax looks like a normal function declaration without the name, assigned to a variable. Note the semicolon after the closing brace: it's an assignment statement.

PHP Storing a function in a variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
HELLO!
Closure
HEY!!
upper: CLOSURE
reverse: erusolc

$shout('hello') calls the closure stored in $shout. A function that takes or returns other functions, like applyTwice, is called a higher-order function. The fn syntax in the array is an arrow function, explained below.

The most common use by far is a callback for a built-in function:

PHP Closures as callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints 23.99, 6, 144.6, 50.4, then 120.5, 42, then 120.5, 42, 19.99, 5. You'll explore these functions in array_map, array_filter and array_reduce and Sorting Arrays.

Capturing variables with use

Like any function, a closure has its own scope and can't see outer variables. The use clause imports them:

PHP Importing variables with use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both calls print bool(true). By default, use captures the variable's value at the moment the closure is created. Changing $minimumAge afterward doesn't affect the closure, which still holds 18. This is usually what you want: the closure behaves the same no matter what happens around it later.

Capturing by reference

To share the variable itself, so the closure sees later changes and can modify it, capture by reference with &:

PHP use by value vs by reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
after by-value: 0
after by-reference: 15
1 2 3 | 1

makeCounter() shows the real power of closures: the returned function keeps $count alive after makeCounter() has returned, and each counter has its own private $count. That's what "closure" means: the function closes over the variables it captured.

Capture by reference only when you need it. A by-value closure is a self-contained snapshot; a by-reference one can change your variables from far away, which brings back the "action at a distance" problem of globals.

Arrow functions: fn (PHP 7.4)

Most callbacks are one expression. Arrow functions give them a compact syntax: fn (params) => expression. The expression's value is returned automatically, and there's no return keyword or braces.

Arrow functions also capture outer variables automatically, by value, with no use clause:

PHP Arrow functions capture automatically

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

print_r shows [book] => 1.8, [lamp] => 6 and [pen] => 0.375, and the last line prints 42.

Rules for arrow functions:

  • The body is one expression only. For several statements, use a regular closure.
  • Capture is always by value. An arrow function can't modify outer variables: fn () => $count++ increments its own copy.
  • Only variables actually used in the expression are captured.
  • Parameter and return types work as usual: fn (int $n): int => $n * 2.

Callables: everything PHP can call

The callable type accepts more than closures. Several kinds of values count as callables:

PHP The many forms of callables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
function name string   php!
built-in function      Php
object method array    **php**
static method string   "php"
static method array    "php"
invokable object       [php]
closure                <php>
bool(false)

An object with an __invoke() method can be called like a function (more in Magic Methods). is_callable() checks whether a value can be called before you try. Strings and arrays as callables are an old convention: they work, but editors can't follow them, renaming a method won't update them, and a typo only fails at runtime. Modern PHP has a better way.

First-class callable syntax (PHP 8.1)

Writing a call with ... in place of the arguments, like strlen(...), creates a Closure from any function or method without calling it:

PHP First-class callables with (...)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints 7, Closure, then the slugs hello-world, php-8-5-is-here and closures-you, then AB. Compared with 'strlen' or [$slugger, 'slugify'], the (...) form is checked when it runs (a missing function fails right there, not later), works with editor navigation and refactoring, and respects visibility: a private method made into a closure inside its class can be passed outside safely.

Before 8.1, Closure::fromCallable('strlen') did the same job; you'll still see it in older code. Static methods work too: Formatter::quote(...).

Closures and $this

A closure created inside a class method automatically has access to $this, so it can call private methods of the object. If a closure doesn't need $this, mark it static function or static fn so it doesn't keep the object alive. This matters once you work with classes; see Classes, Properties and Methods.

PHP
class Cart
{
    private array $items = [];

    public function totalWith(float $rate): float
    {
        // $this is available inside the arrow function
        return array_sum(array_map(fn (array $item) => $this->lineTotal($item) * (1 + $rate), $this->items));
    }

    private function lineTotal(array $item): float
    {
        return $item['price'] * $item['qty'];
    }
}

Practical patterns: factories and composition

Two patterns show up constantly once you're comfortable with closures. A function factory builds specialized functions from parameters, and composition chains small functions into a pipeline. PHP 8.5's pipe operator |> passes a value through a chain of single-argument callables from left to right, which pairs naturally with closures and first-class callables:

PHP Function factories and pipelines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
ab        must be at least 3 characters
Bad Name  may only contain a-z, 0-9 and _
good_name OK
hello-closures-world

minLength(3) and matches(...) each return a closure that remembers its own settings, so rules are values you can store in arrays, reuse and combine. In the pipeline, each step receives the previous result; an arrow function in a pipe must be wrapped in parentheses. The pipe operator is covered in Bitwise, String, Array and Pipe Operators.

When to use which

  • Arrow function for short, one-expression callbacks: array_map(fn ($x) => $x * 2, $list).
  • Closure with use when the body needs several statements, or when you need to modify a captured variable by reference.
  • First-class callable (strlen(...), $obj->method(...)) when a named function already does the job.
  • Named function when the logic is reused in several places or deserves its own name and tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? $n = 1; $f = function () use ($n) { return $n; }; $n = 2; echo $f();

    use captures the value when the closure is created. Later changes to $n don't affect the closure.
  2. 2. What does this print? $n = 1; $f = function () use (&$n) { return $n; }; $n = 2; echo $f();

    Capturing by reference shares the variable, so the closure sees the current value 2.
  3. 3. How do arrow functions (fn) capture outer variables?

    Arrow functions capture every outer variable they use, by value. They can't modify the outer variables.
  4. 4. What does $f = strlen(...); do?

    The first-class callable syntax (PHP 8.1) turns any function or method into a Closure object.
  5. 5. Which value is NOT a valid callable?

    An array callable needs two elements, an object or class name and a method name. A one-element array can't be called.

Summary

  • Anonymous functions are Closure objects you can store, pass and return. End the assignment with a semicolon.
  • use ($x) imports outer variables by value at creation time; use (&$x) shares them by reference.
  • Closures can keep private state alive, like a counter returned from a factory function.
  • Arrow functions fn ($x) => expr (7.4) are single expressions that capture outer variables automatically, by value.
  • Callables include function-name strings, [$object, 'method'], 'Class::method', invokable objects and closures; check them with is_callable().
  • First-class callable syntax strlen(...) and $obj->method(...) (8.1) creates closures safely; prefer it over string and array callables.

Next: Recursion