Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Closure capture by reference

Closure use by reference binds a closure to the outer variable through use (&$count).

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

function () use (&$count) { ++$count; }

Closure use by reference binds a closure to the outer variable through use (&$count). Later reassignment of the outer value is visible to the closure, and assignment inside changes that same variable. A by-value use captures the value at creation for the integer in this example. Reinvoking the reference-capturing closure continues from the shared value.

$count = 2;
$snapshot = function () use ($count) { return $count; };
$bump = function () use (&$count) { return ++$count; };
$count = 8;
echo json_encode([$snapshot(), $bump(), $bump(), $count]);
[2,9,10,10]

Examples

<?php
$count = 2;
$snapshot = function () use ($count) { return $count; };
$bump = function () use (&$count) { return ++$count; };
$count = 8;
echo json_encode([$snapshot(), $bump(), $bump(), $count]);

Result

[2,9,10,10]

Sources