CKTIS / PHP
Pass-by-reference parameter (`&$response`)
A parameter declared as `&$response` lets a PHP function change the caller’s variable. Put `&` in the parameter declaration, not at the call site.
Version: PHP 8.3; extension availability may vary
Syntax
function setResponse(string &$response): void { /* Assign to $response here. */ }
setResponse($message);In PHP 8.3, a pass-by-reference parameter (&$response) lets the function write to the caller’s variable. In setResponse($message), $response and $message are two names for the same stored value. An assignment to $response is therefore visible in $message after the function ends. With the default pass-by-value behavior, that assignment would not change $message.
Put & only in the parameter declaration, not on the argument. Pass a variable such as $message. Calling setResponse('pending') raises an error because a literal is not a variable. You can also pass the result of a function that returns by reference, but an ordinary function result should not be passed this way.
$response is an ordinary parameter name; it has no connection to HTTP. : void means the function returns no value; changing $message is a side effect of the call. If the function only needs to produce one new value, consider returning it and assigning it explicitly in the caller.
Examples
<?php
function setResponse(string &$response): void
{
$response = 'ready';
}
$message = 'pending';
echo "Before: $message\n";
setResponse($message);
echo "After: $message\n";
Result
Before: pending After: ready
The first line shows `pending` and the second shows `ready`. The call changes `$message` even though the function returns no value.
Related lessons
- PHP · Lesson 26 · Intermediate · Version: 3