Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Capturing by reference in a PHP closure: `use (&$vat)`

In PHP, `use (&$vat)` lets a closure share a variable with the scope where the closure was created. Without `&`, the closure keeps the scalar value from creation time.

Version: PHP 8.3; extension availability may vary

Syntax

$closure = function () use (&$vat): int { return $vat; };

The phrase closure capture by reference use (&$vat) describes how use (&$vat) captures $vat from the scope where the closure is created, not where it is called. The inner and outer $vat are aliases for the same variable: an assignment outside is visible inside, and an assignment inside changes what the outer scope sees. Here & marks reference capture, not a by-reference parameter or bitwise AND. This use clause does not import namespace names.

use ($vat) captures by value. For an integer, the closure keeps the value from creation time, not call time. Later assignments outside do not update the capture, and assignments inside do not update the outer variable. By-value capture is not a deep copy: with an object, you can still modify properties of the same object.

In PHP 8.3, put the use clause after the parameter list and before any return type. In the syntax shown, the value returned from $vat must satisfy the declared int return type when the closure is called. The capture list cannot include $this, superglobals, or parameter names. A closure can retain access to the captured value after its defining scope exits. Calling unset($vat) outside removes only the outer binding; the closure still has access to the shared value.

Use a reference only when shared mutable state is intentional: the result of a call can then depend on earlier writes and on call order.

Examples

<?php
$vat = 20;

$snapshot = function () use ($vat): int {
    return $vat;
};

$live = function () use (&$vat): int {
    return $vat;
};

$bump = function () use (&$vat): void {
    $vat += 1;
};

$vat = 23;
echo 'snapshot=', $snapshot(), ' live=', $live(), "\n";

$bump();
echo 'outer=', $vat, ' live=', $live(), ' snapshot=', $snapshot(), "\n";

Result

snapshot=20 live=23
outer=24 live=24 snapshot=20

After the outer assignment to `23`, `$live()` returns `23` while `$snapshot()` still returns `20`. Calling `$bump()` raises the shared value to `24`, which both the outer `$vat` and `$live()` see.

Related lessons

  • PHP · Lesson 4 · Advanced · Version: 2

Sources