CKTIS / PHP
By-reference parameter `&$res`
The ampersand before `$res` lets a function change the variable supplied by its caller instead of returning a replacement value.
Version: PHP 8.3; extension availability may vary
Syntax
function writeSum(int $left, int $right, int &$res): void { /* ... */ }
$total = 0;
writeSum(2, 3, $total);In a function signature, the reference parameter &$res makes the local name $res an alias for the caller's variable during the call. Assigning to $res changes that variable, unlike ordinary pass-by-value. res is an ordinary name, not a keyword; & here marks neither a pointer nor a return by reference.
Put & in the declaration, not at the call site: write writeSum(2, 3, $total). For the by-reference argument, use a variable, not a literal such as 0 or a computed expression such as 2 + 3. A reference returned by a function declared to return by reference can also be passed.
In PHP 8.3, the type in int &$res is checked on entry, not again when the function returns. The declaration alone therefore does not guarantee that the variable still holds an int afterward. unset($res) inside the function removes only the local binding, not the caller's variable.
Document which arguments a function may overwrite. If you only need to produce one result and do not need to change the caller's variable, an ordinary return is usually clearer. This is PHP language syntax and needs no additional extension.
Examples
<?php
declare(strict_types=1);
function writeSum(int $left, int $right, int &$res): void
{
$res = $left + $right;
}
$total = 0;
echo "before: ", $total, "\n";
writeSum(2, 3, $total);
echo "after: ", $total, "\n";
Result
before: 0 after: 5
`$total` starts at `0`. Assignment through `$res` changes it to `5`, even though `writeSum()` has return type `void` and returns no result.
Related lessons
- PHP · Lesson 70 · Advanced · Version: 2