KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / PHP

Variabelen per referentie vastleggen in een closure

Met use (&$count) wordt de closure aan de buitenste variabele gekoppeld (`Closure use by reference`).

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

Syntax

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

Met use (&$count) wordt de closure aan de buitenste variabele gekoppeld (Closure use by reference). Latere toewijzingen buiten de closure zijn binnen zichtbaar en een wijziging binnen werkt naar buiten door. Voor het gehele getal legt use ($count) de waarde bij het aanmaken vast.

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

Voorbeelden

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

Resultaat

[2,9,10,10]

Bronnen