CKTIS / PHP
Returning by reference: `function &getSession`
A function that returns by reference lets the caller alias a variable. Use `=&` to bind the alias; plain `=` assigns the value without creating that binding.
Version: PHP 8.3; extension availability may vary
Syntax
function &getSession(): array { static $state = []; return $state; }
$alias = &getSession(); // Bind an alias to the returned variable.
$copy = getSession(); // Assign the array by value.In PHP 8.3, reference return (function &getSession) means that the & before the function name declares a reference return. In function &getSession(): array, array specifies the return type. Use return $state; to name the variable, without adding & after return. A literal or the result of a calculation is not a variable and cannot validly be returned by reference.
$alias = &getSession(); binds another name to the same variable. Changing $alias['visits'] changes the stored array. In contrast, $copy = getSession(); assigns the array by value, so changing $copy['visits'] does not change the original. This is not passing an argument by reference: the declaration's & applies to the result, and =& binds the alias on the caller's side.
getSession() is defined in the example; it is not a built-in session API. Its local static variable retains its value between calls in the same run but does not store data across requests. The example needs no session extension. Starting or resuming an actual PHP session manually requires session support and a successful session_start() call; the session data is available in $_SESSION.
Return a reference only when the caller should be able to change the underlying state directly, not as a performance trick. If changes need validation, expose a separate update function instead of a writable alias.
Examples
<?php
function &getSession(): array
{
static $state = ['visits' => 1];
return $state;
}
$copy = getSession();
$alias = &getSession();
$alias['visits']++;
$copy['visits'] += 10;
$current = getSession();
echo 'Stored: ', $current['visits'], "\n";
echo 'Copy: ', $copy['visits'], "\n";
Result
Stored: 2 Copy: 11
Changing the alias raises the stored `visits` to `2`. The copy was taken earlier, so adding `10` to it gives `11` without changing the original.
Related lessons
- PHP · Lesson 25 · Intermediate · Version: 3