ZetCode

PHP fn Keyword

last modified November 25, 2026

The PHP fn keyword declares an arrow function, a compact closure whose body is a single expression. Arrow functions capture the variables they use from the surrounding scope automatically, so a callback that would need a use clause as a closure needs nothing extra as an arrow function.

This article covers the syntax, implicit capture by value, the one-expression rule, callbacks, nested functions, $this and static fn, and precedence. The arrow functions and closures tutorials cover the wider subject.

Basic definitions

An arrow function is a short closure. The fn keyword introduces the parameter list, the => operator separates it from the body, and the body is a single expression whose value becomes the return value.

The syntax is fn (parameters): returnType => expression. The return type is optional, and parameter types and default values work as they do in named functions. There is no use clause: an arrow function captures every variable it needs from the surrounding scope automatically, by value, at the moment it is created.

The result is an object of the Closure class, so it can be stored in a variable, passed to a function such as array_map, or returned. The static fn form declares an arrow function without access to $this. The arrow functions and closures articles cover the wider topic; this page concentrates on the keyword and its rules.

A first arrow function

The first example stores an arrow function in a variable, calls it, and passes a second one to array_map.

fn_first.php
<?php

declare(strict_types=1);

$double = fn(int $n): int => $n * 2;

echo $double(21), "\n";
echo get_debug_type($double), "\n";

$squares = array_map(fn(int $n): int => $n ** 2, [1, 2, 3, 4]);
echo implode(", ", $squares), "\n";

$double is a Closure object, and calling it with $double(21) runs the expression $n * 2. The expression value is returned without a return keyword. array_map applies $n ** 2 to each element and returns a new array, which implode turns into one line.

$ php fn_first.php
42
Closure
1, 4, 9, 16

Capturing the parent scope

An arrow function captures the variables it uses when it is defined, not when it is called. The captured value is a copy, and the body works on that copy.

fn_capture.php
<?php

declare(strict_types=1);

$limit = 10;

$atLimit = fn(int $n): bool => $n >= $limit;

$limit = 100;
echo var_export($atLimit(50), true), "\n";
echo var_export($atLimit(5), true), "\n";

$counter = 1;
$next = fn(): int => $counter++;

echo $next(), " ", $next(), " ", $next(), "\n";
echo "outside: ", $counter, "\n";

$atLimit captures $limit while it is 10. Changing $limit to 100 afterwards does not affect the closure, so 50 is still above the captured limit and 5 is not. This is capture by value, and it is the reason an arrow function needs no use list.

The counter example shows the same rule from the other side. Each call starts from the captured value 1 and increments its own copy, so the function returns 1 every time, and $counter in the outer scope stays 1. State that has to survive between calls belongs in an object property, a static variable, or a closure created with function () use (&$counter).

$ php fn_capture.php
true
false
1 1 1
outside: 1

The body is one expression

Because the body of an arrow function is an expression, a block with braces and a return statement is not allowed. The next listing is rejected while the file is parsed.

fn_block_error.php
<?php

declare(strict_types=1);

$add = fn(int $a, int $b): int => $a + $b;

echo $add(2, 3), "\n";

$triple = fn(int $n): int => {
    return $n * 3;
};

echo $triple(5), "\n";

The parser stops at the opening brace, because the => operator expects an expression. To run several statements, use a closure with a block body, or keep the arrow function to one expression and extract the rest into a named function. An array literal is an expression, so fn(int $n) => [$n, $n * 2] is fine.

$ php fn_block_error.php
Parse error: syntax error, unexpected token "{" in /app/fn_block_error.php on line 9

Callbacks with array_map and array_filter

Arrow functions are most often used where a callback is expected. The next example maps prices, filters an array, and combines two arrays.

fn_array_map.php
<?php

declare(strict_types=1);

$prices = [10, 25, 40];

$withTax = array_map(fn(float $p): float => round($p * 1.2, 2), $prices);
echo implode(", ", $withTax), "\n";

$larger = array_filter($prices, fn(int $p): bool => $p > 10);
echo implode(", ", $larger), "\n";
print_r(array_keys($larger));

$combined = array_map(
    fn(string $name, int $age): string => "$name ($age)",
    ["Alice", "Bob"],
    [30, 25]
);
print_r($combined);

array_map returns a new array with the same keys. array_filter keeps the keys of the elements it keeps, so the two prices that pass the test stay at keys 1 and 2 instead of moving to 0 and 1; array_keys shows that explicitly. Calling array_values would renumber the result when a plain list is wanted.

With two input arrays, array_map passes one element from each array to the callback, so the arrow function takes two parameters. The arrays are walked in parallel and the result has the length of the longest one, with null filling missing values on the shorter side.

$ php fn_array_map.php
12, 30, 48
25, 40
Array
(
    [0] => 1
    [1] => 2
)
Array
(
    [0] => Alice (30)
    [1] => Bob (25)
)

Nested arrow functions

An arrow function may return another arrow function. The inner function captures the parameters of the outer one, which is a compact way to build a configured callback.

fn_nested.php
<?php

declare(strict_types=1);

$adder = fn(int $a): callable => fn(int $b): int => $a + $b;

$addTen = $adder(10);
echo $addTen(5), "\n";
echo $adder(2)(3), "\n";

$multiplier = fn(int $factor): callable => fn(int $value): int => $value * $factor;

echo $multiplier(3)(7), "\n";

$adder(10) returns a closure with $a fixed at 10, and the returned closure adds its own argument to that value. The double call $adder(2)(3) does both steps at once. Each level captures by value, so the functions are independent of later changes to the outer variables.

$ php fn_nested.php
15
5
21

Arrow functions in methods

An arrow function created inside a method captures $this automatically, so it can read private properties of the object. The static fn form has no $this and is the right choice for a callback that must not depend on the object.

fn_object.php
<?php

declare(strict_types=1);

class Greeter
{
    public function __construct(private string $name)
    {
    }

    public function callback(): Closure
    {
        return fn(string $greeting): string => "$greeting, {$this->name}";
    }

    public function staticCallback(): Closure
    {
        return static fn(string $value): string => strtoupper($value);
    }
}

$greeter = new Greeter("Alice");

$callback = $greeter->callback();
echo $callback("Hello"), "\n";

echo $greeter->staticCallback()("hi"), "\n";

The first closure prints the private $name through {$this->name}, because the capture happens inside the method that owns the property. The second one is declared static: it receives a string and returns an uppercase version without touching the object. Both are returned as Closure instances and called from outside the class.

$ php fn_object.php
Hello, Alice
HI

The static form and $this

A static arrow function is not bound to an object. If its body mentions $this, the error appears only when the function is called, not when it is declared.

fn_static_error.php
<?php

declare(strict_types=1);

class Greeter
{
    public function __construct(private string $name)
    {
    }

    public function callback(): Closure
    {
        return static fn(): string => $this->name;
    }
}

$callback = (new Greeter("Alice"))->callback();
echo $callback(), "\n";

The declaration is accepted, but the call fails with Error: Using $this when not in object context. The same rule applies to a static closure written with function. Use static fn deliberately: it documents that the callback is independent of the instance and prevents an accidental dependency on it.

$ php fn_static_error.php
Fatal error: Uncaught Error: Using $this when not in object context in /app/fn_static_error.php:13
Stack trace:
#0 /app/fn_static_error.php(18): Greeter::{closure:Greeter::callback():13}()
#1 {main}
  thrown in /app/fn_static_error.php on line 13

Precedence and immediate calls

An arrow function is an expression, so it can be called immediately when it is wrapped in parentheses. The same rule applies when the function appears inside a larger expression.

fn_precedence.php
<?php

declare(strict_types=1);

echo (fn(int $n): int => $n * 2)(21), "\n";

$choose = true
    ? fn(int $n): int => $n + 1
    : fn(int $n): int => $n - 1;

echo $choose(10), "\n";

$makeList = fn(int $n): array => [$n, $n * 2, $n * 3];
echo implode(", ", $makeList(4)), "\n";

Without the parentheses around the declaration, the call would attach to the last value in the expression instead of to the whole function, so the parentheses are required. An arrow function also extends as far to the right as possible, which is why the ternary arms are written on separate lines. Assigning the function to a variable first is the most readable option when the expression grows.

$ php fn_precedence.php
42
11
4, 8, 12

Arrow function or closure

Both forms produce a Closure, and the choice is mostly about the body. The table summarizes the differences.

Featurefnfunction
Bodyone expressionblock with statements
Captureautomatic, by valueexplicit use
$thisautomaticautomatic
Returnthe expression valuereturn statement
Best forshort callbacksmulti-step logic and state

Best practices

Keep arrow functions small and predictable.

Source

PHP manual: arrow functions

PHP manual: anonymous functions

PHP manual: array_map

PHP manual: array_filter

This article covered the PHP fn keyword: its syntax, implicit capture, the expression body, callbacks, nesting, and the static form. Continue with PHP arrow functions for more patterns, or read PHP closures for capture by reference and binding.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.