CKTIS / PHP
Assignment by reference: `$session = &getSession()`
Learn how the two ampersands create an alias for a variable returned by a function, and why this does not start a PHP session.
Version: PHP 8.3; extension availability may vary
Syntax
function &getSession(): array {
static $data = [];
return $data;
}
$session = &getSession();In PHP 8.3, reference assignment ($session = &getSession()) binds $session to the contents of the returned variable instead of assigning just its value. Both names access the same contents, so writes through either name are visible through the other. getSession() calls the function with no arguments. By contrast, getSession(...) is first-class callable syntax: it creates a Closure without calling the function.
Two ampersands are needed: the & before the name in function &getSession(): array declares a return by reference, and the & after = binds that result to $session. This is neither bitwise AND nor passing an argument by reference. Return a variable, as in return $data;, not a literal or a calculated result. If the function returns by value, adding & only at the assignment produces a diagnostic and does not create an alias.
Here getSession() is a user-defined function in the global namespace, not a PHP built-in. Its local static array keeps its value between calls in one script run. Plain $copy = getSession(); creates no alias, so changing the counter in the copy leaves the stored array unchanged. unset($session) removes the alias name, not the stored array. Return a reference when callers are meant to modify shared contents, not for performance.
The example uses neither $_SESSION nor the session extension. For a real session that is not already active, check that session_start() succeeds before relying on $_SESSION. Extension availability depends on the installation. Store session data, not aliases that you expect to survive across requests.
Examples
<?php
function &getSession(): array
{
static $data = ['count' => 0];
return $data;
}
$session = &getSession();
$session['count']++;
$copy = getSession();
$copy['count'] = 9;
echo 'stored=', getSession()['count'], "\n";
echo 'copy=', $copy['count'], "\n";
unset($session);
echo 'after unset=', getSession()['count'], "\n";Result
stored=1 copy=9 after unset=1
Incrementing through `$session` sets the stored counter to `1`. Only the copy gets `9`; after `unset($session)`, the stored counter is still `1`.
Related lessons
- PHP · Lesson 25 · Intermediate · Version: 3