CKTIS / PHP
Pass-by-reference parameter: &$session
Putting `&` before `$session` lets the function modify the caller’s array directly. The parameter does not start a PHP session or save its data.
Version: PHP 8.3; extension availability may vary
Syntax
function recordVisit(array &$session): void { /* update $session */ }
recordVisit($state);In PHP 8.3, a pass-by-reference parameter (&$session) makes the local name $session and the caller’s argument variable refer to the same value. Changing an array entry or replacing the whole array affects the caller, even though the function returns void. Without &, an ordinary array is passed by value by default, so those changes stay local.
Put & in the parameter declaration, not at the call site: recordVisit($state). Pass a variable, not an array literal such as []. The array type is checked on entry, not on return; an argument of the wrong type causes a TypeError.
$session is just a parameter name, not the $_SESSION superglobal. If the session extension is available, you can call recordVisit($_SESSION) after session_start() succeeds. PHP’s session handling, not &, saves the session data; do not rely on reference relationships being restored across requests. The console example does not need the session extension.
Examples
<?php
function recordVisit(array &$session): void
{
$session['visits'] = ($session['visits'] ?? 0) + 1;
}
$state = [];
recordVisit($state);
echo $state['visits'], "\n";
recordVisit($state);
echo $state['visits'], "\n";
Result
1 2
The ordinary array `$state` starts empty. Its counter is `1` after the first call and `2` after the second; no PHP session is started.
Related lessons
- PHP · Lesson 25 · Intermediate · Version: 3