CKTIS / PHP
Assignment by reference: $alias and $projects
Assignment by reference gives two names to the same value. Writing through either name changes the shared value; `unset($alias)` removes only the alias binding.
Version: PHP 8.3; extension availability may vary
Syntax
$alias =& $projects;In PHP 8.3, reference assignment ($alias =& $projects) makes $alias and $projects two equally valid names for the same value. $alias = &$projects; means the same thing. Neither name is a pointer to the other. Assignment by reference is part of the language and needs no extension.
Appending through $alias[] changes the array you read through $projects. Assigning a new array to $projects with plain = replaces the shared value without breaking the binding. By contrast, $copy = $projects assigns by value: it does not alias the array as a whole, although references stored in its elements are preserved.
On the right of =&, use a variable such as $projects, not an array literal or the result of a function that returns by value. Initialize $projects before creating the alias: if the variable does not exist, assignment by reference creates it with the value null.
unset($alias) removes only that name's binding; $projects keeps its value. A later assignment to $alias creates an independent variable. Without first using unset, $alias = null changes the shared value to null rather than detaching the name. Use an alias when you intentionally want both names to be able to change the same value.
Examples
<?php
$projects = ['Atlas'];
$copy = $projects;
$alias =& $projects;
$alias[] = 'Orion';
echo '$projects: ', implode(', ', $projects), "\n";
echo '$copy: ', implode(', ', $copy), "\n";
$projects = ['Nova'];
echo '$alias: ', implode(', ', $alias), "\n";
unset($alias);
$alias = ['Vega'];
echo '$projects: ', implode(', ', $projects), "\n";
echo '$alias: ', implode(', ', $alias), "\n";
Result
$projects: Atlas, Orion $copy: Atlas $alias: Nova $projects: Nova $alias: Vega
Appending `Orion` through `$alias` changes `$projects` but not `$copy`. Replacing `$projects` with the array containing `Nova` is visible through `$alias`. After `unset($alias)`, assigning the array containing `Vega` leaves `$projects` unchanged.
Related lessons
- PHP · Lesson 22 · Intermediate · Version: 3