CKTIS / PHP
Pass-by-reference parameters (&$tasks, &$used)
Adding `&` to the `$tasks` and `$used` parameters lets the function update both caller variables without returning them.
Version: PHP 8.3; extension availability may vary
Syntax
function addTask(array &$tasks, array &$used, string $name): void { /* ... */ }
addTask($tasks, $used, 'Review');The label pass-by-reference parameter (&$tasks, &$used) refers to the & immediately before each parameter name. In PHP 8.3, write array &$tasks, array &$used in the declaration, but leave out & when calling addTask($tasks, $used, 'Review'). There is no & on $name, so its argument is passed by value, the default.
During the call, each reference parameter is a local alias for the variable the caller passed. Changing an array element or assigning a new value to the parameter changes the caller's variable. Those changes remain visible after the call, even with a void return type. An & on a parameter does not mean the function returns by reference.
Use initialized variables for the simplest calls. A function call that returns by reference can also supply an argument. Do not pass a literal such as [] or an ordinary expression result in place of $tasks or $used; a literal in that position causes an error.
The array declaration is checked on entry: passing a variable that does not contain an array causes a TypeError. PHP does not recheck these parameter types when the function returns. Document which arguments your function changes, since this is not visible at the call site. This feature requires no additional extension.
Examples
<?php
function addTask(array &$tasks, array &$used, string $name): void
{
$tasks[] = $name;
$used[$name] = true;
}
$tasks = [];
$used = [];
addTask($tasks, $used, 'Review');
echo $tasks[0], "\n";
echo $used['Review'] ? "used\n" : "unused\n";
Result
Review used
After the call, `$tasks[0]` contains `Review` and `$used['Review']` is `true`. The script therefore prints `Review` followed by `used` on the next line.
Related lessons
- PHP · Lesson 12 · Basic · Version: 2