Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Capturing a variable by reference in a closure: `use (&$MAP)`

`use (&$MAP)` lets an anonymous function read and update the current state of `$MAP` from the scope where the function was defined.

Version: PHP 8.3; extension availability may vary

Syntax

$increment = function (string $key) use (&$MAP): int {
    return ++$MAP[$key];
};

In PHP 8.3, closure capture by reference use (&$MAP) is written after an anonymous function’s parameter list and before its optional return type. $MAP is an ordinary variable name; in the example it holds an associative array, which maps keys to values. Here & marks a reference, not a bitwise operation.

The binding is made when the closure is created, in the defining scope, not the caller’s scope. While both bindings remain in place, replacing the array outside is visible inside, and writing an entry inside is visible outside. In contrast, use ($MAP) captures the example’s array of integers by value at creation time. An arrow function (fn) automatically captures the outer variables it uses by value.

This use clause is not a namespace import. It is also not a by-reference parameter such as function (array &$map), which binds a variable supplied at call time. In the example, the only argument is the key.

The closure can retain access to the captured state after the defining scope has exited. Calling unset($MAP) outside removes only the outer binding; recreating $MAP will not reconnect it to the existing closure. Initialize the map before capture. Use & only when the function is meant to share state with the surrounding code.

Examples

<?php
$MAP = ['apples' => 1];

$readSnapshot = function () use ($MAP): int {
    return $MAP['apples'];
};

$increment = function (string $key) use (&$MAP): int {
    return ++$MAP[$key];
};

$MAP = ['apples' => 2];
echo $readSnapshot(), "\n";
echo $increment('apples'), "\n";
echo $MAP['apples'], "\n";

Result

1
3
3

The first read gives `1` from the array captured by value. After the map is replaced, the reference-capturing closure sees `2` and increments the existing `apples` entry to `3`. The outer read also gives `3`. The example requires no additional extension.

Related lessons

  • PHP · Lesson 36 · Intermediate · Version: 3

Sources