Closures and arrow functions

A closure is a function that a program builds and passes around as a value. In PHP the value can capture the variables it needs, which keeps small helpers next to the code that uses them.

Anonymous functions

A closure is a function value without a name. Store it in a variable and call it like a normal function. It keeps code local when a helper is needed only once.

Add parameter and return types exactly as you would for a named function.

<?php $add = function (int $a, int $b): int { return $a + $b; }; echo $add(2, 3), PHP_EOL;

php closure.php

5

The variable holds the closure and the parentheses after it run the body. The same value can be passed to a function that expects a callable, which a named function cannot do in an expression.

Capture with use

Closures do not see outer variables by default. List needed names in a use clause to capture them by value at creation time.

Capture keeps the data flow explicit and avoids hidden dependence on globals.

<?php $factor = 3; $mul = function (int $x) use ($factor): int { return $x * $factor; }; echo $mul(10), PHP_EOL;

php use.php

30

The closure keeps the value of $factor from the moment it was built, so a later change of the outer variable does not reach it. The & in front of a name in the clause captures a reference instead, and the prose of the quiz below warns about that difference.

fn arrow functions

The short fn form fits one expression callbacks. It captures outer variables automatically by value, so no use clause is needed.

Use it for mapping, filtering, and sorting where the logic fits on one line.

<?php $factor = 3; $mul = fn(int $x): int => $x * $factor; $nums = [1, 2, 3]; echo implode(",", array_map($mul, $nums)), PHP_EOL;

php arrow.php

3,6,9

array_map() calls the arrow function once for each number, and implode() joins the results. The arrow form reads the outer $factor without a clause, because it always captures by value.

Pass callables around

Many core functions accept a callable to customize behavior. Pass a closure, an arrow function, a function name as a string, or an array with an object and a method name.

Modern PHP also offers first-class callable syntax with three dots, which creates a closure from any callable without writing a wrapper.

<?php $words = ["pear", "apple", "fig"]; usort($words, fn(string $a, string $b): int => strlen($a) <=> strlen($b)); $fn = strlen(...); echo implode(",", $words), PHP_EOL; echo $fn("hello"), PHP_EOL;

php callable.php

fig,pear,apple
5

usort() reorders the list with the comparison of the arrow function, so the shortest word comes first. The three dots build a closure from strlen() itself, and the call on the next line proves it.

Partial function application (PHP 8.6)

PHP 8.6 adds one more way to create a closure: call a function and put a placeholder where an argument is still unknown. The call does not run the function. It returns a closure that waits for the missing arguments.

A ? leaves exactly one argument open, and ... leaves all the remaining ones open. The code below needs PHP 8.6.

<?php function greet(string $greeting, string $name): string { return "$greeting, $name!"; } $hello = greet("Hello", ?); var_dump(get_class($hello)); var_dump($hello("Anna")); $toAnna = greet(?, "Anna"); var_dump($toAnna("Hi")); $bye = greet("Bye", ...); var_dump($bye("Bob"));

string(7) "Closure"
string(12) "Hello, Anna!"
string(9) "Hi, Anna!"
string(9) "Bye, Bob!"

On PHP 8.5 the same line stops the parser with PHP Parse error: syntax error, unexpected token "?", expecting ")", because the placeholder arrived in 8.6. The page shows the 8.6 output and the run of this block is listed as not run in the notes of the course.

... can stand for several arguments at once. The closure takes all of them in the order of the function signature, and any arguments written before it stay fixed:

<?php function order( string $buyer, string $item, int $count, float $price ): string { $total = $count * $price; return "$buyer: $count x $item = $total"; } $forAnna = order("Anna", ...); var_dump($forAnna("pen", 3, 1.5)); $bobBooks = order("Bob", "book", ...); var_dump($bobBooks(2, 12.5));

string(19) "Anna: 3 x pen = 4.5"
string(18) "Bob: 2 x book = 25"

The first closure takes the three remaining arguments in signature order, and the second one fixes two of them and waits for the count and the price. Neither call runs order() until the closure is called. On PHP 8.5 this file stops with PHP Parse error: syntax error, unexpected token ")" at the first placeholder.

Exercises

  1. Change $factor after the closure is built in use.php and run it. Which value does the call see?
  2. Rewrite the closure of use.php as an arrow function and compare the two files.
  3. Filter a list with array_filter() and an arrow function that keeps the long words.
  4. Pass "strtoupper" to array_map() as a string and print the result.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which outer variables does a closure see by default?

    Answer

    None of them

    A closure starts with its own scope, and the use clause is what brings a name in.

  2. What does use ($factor) capture?

    Answer

    The value the variable had when the closure was built

    The clause copies the value at creation time; a later change of the outer variable stays outside.

  3. What is special about the fn arrow form?

    Answer

    It captures outer variables automatically and holds one expression

    An arrow function is one expression with automatic capture by value, so the use clause is not written.

  4. What does strlen(...) create?

    Answer

    A closure made from the function

    The three dots are the first-class callable syntax, which turns any callable into a closure.

  5. What does this program print? <?php $add = function (int $a, int $b): int { return $a + $b; }; echo $add(2, 3);

    Answer

    5

    The closure adds its two arguments, and the echo prints the sum.

  6. What does this program print? <?php $factor = 3; $mul = function (int $x) use ($factor): int { return $x * $factor; }; echo $mul(10);

    Answer

    30

    The captured factor is 3, and the argument 10 is multiplied by it.

  7. What does this program print? <?php $factor = 3; $mul = fn(int $x): int => $x * $factor; $nums = [1, 2, 3]; echo implode(",", array_map($mul, $nums));

    Answer

    3,6,9

    array_map applies the arrow function to each number and implode joins the three results.

  8. What does this program print? <?php $words = ["pear", "apple", "fig"]; usort($words, fn(string $a, string $b): int => strlen($a) <=> strlen($b)); $fn = strlen(...); echo implode(",", $words), PHP_EOL; echo $fn("hello");

    Answer

    fig,pear,apple / 5

    usort orders the words by length, and the closure made from strlen returns the length of hello.

  9. What does this program print? <?php $factor = 3; $mul = function (int $x) use ($factor): int { return $x * $factor; }; $factor = 10; echo $mul(2);

    Answer

    6

    The use clause copied the value 3 when the closure was built, so the later assignment does not change it.

  10. What does this program print? <?php function double(int $n): int { return $n * 2; } $nums = [1, 2, 3]; echo implode(",", array_map("double", $nums));

    Answer

    2,4,6

    A function name as a string is a valid callable, so array_map runs double on each number.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above. The partial application blocks need PHP 8.6 and were not run here.

Article authors: Arthur Isaev, Andrei Olegovich, Klavdiya Kondakova