WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / PHP

Variablen per Referenz in Closures übernehmen

Mit use (&$count) bindet die Closure die äußere Variable per Referenz (`Closure use by reference`).

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

Syntax

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

Mit use (&$count) bindet die Closure die äußere Variable per Referenz (Closure use by reference). Spätere Zuweisungen außen sind innen sichtbar, und Änderungen im Funktionskörper wirken nach außen. Für die ganze Zahl erfasst use ($count) dagegen den Wert zum Erstellungszeitpunkt.

$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]

Beispiele

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

Ergebnis

[2,9,10,10]

Quellen