Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Assignment by reference

Reference assignment (= &) makes two names refer to the same variable.

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

Syntax

$alias =& $original;

Reference assignment (= &) makes two names refer to the same variable. Ordinary assignment through either name changes the value observed by both. Rebinding one name by reference to a different variable separates it from the original pair, and unset removes only that name. The example distinguishes an alias from an earlier by-value integer copy.

$x = 1; $copy = $x; $alias =& $x;
$alias = 4;
$y = 8; $alias =& $y; $alias = 9;
unset($alias);
echo json_encode([$x, $copy, $y, isset($alias)]);
[4,1,9,false]

Examples

<?php
$x = 1; $copy = $x; $alias =& $x;
$alias = 4;
$y = 8; $alias =& $y; $alias = 9;
unset($alias);
echo json_encode([$x, $copy, $y, isset($alias)]);

Result

[4,1,9,false]

Sources