CKTIS / PHP
Pass-by-reference parameter (`&$projects`)
`&$projects` lets a function change the caller’s variable. Put `&` in the parameter declaration, not in the call.
Version: PHP 8.3; extension availability may vary
Syntax
function addProject(array &$projects, string $name): void { $projects[] = $name; }
addProject($activeProjects, 'Beacon');In PHP 8.3, array &$projects declares a pass-by-reference parameter (&$projects). During the call, $projects inside the function and $activeProjects in the caller are two names for the same contents. Appending with $projects[] = $name or assigning a whole new array to $projects changes the caller’s variable. The change remains visible after the function returns; void means the function does not return a result.
Put & only in the parameter declaration. Call addProject($activeProjects, 'Beacon') without &. Pass an initialized variable rather than an array literal such as [], which is an error in this position. A reference returned by a function can also be passed; an ordinary return value is not a substitute for a variable.
PHP checks the array type on entry, not on exit. If the initialized variable holds a non-array value, the call throws a TypeError. The parameter declaration itself does not guarantee that the function leaves an array in the variable.
Without &, the argument is passed by value by default: the append in this example would change only the local array. Use a reference when changing the caller’s variable is intentional, and document that effect. If the caller’s variable should remain unchanged, take the array by value and return an updated array.
Examples
<?php
function addProject(array &$projects, string $name): void
{
$projects[] = $name;
}
$activeProjects = ['Atlas'];
echo implode(', ', $activeProjects), "\n";
addProject($activeProjects, 'Beacon');
echo implode(', ', $activeProjects), "\n";
Result
Atlas Atlas, Beacon
The first line shows the state before the call. The second shows that `Beacon` was appended to `$activeProjects` even though `addProject()` returns no result.
Related lessons
- PHP · Lesson 12 · Intermediate · Version: 3
- PHP · Lesson 13 · Intermediate · Version: 3