Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Pass-by-reference parameter (`&$st`)

An ampersand before a parameter name lets the function change the caller’s variable. Write `&$st` in the declaration, but pass the variable normally: `markReady($status)`.

Version: PHP 8.3; extension availability may vary

Syntax

function markReady(string &$st): void { $st .= '!'; }
markReady($status);

In PHP 8.3, string &$st declares a pass-by-reference parameter (&$st). Inside the function, $st is a local alias for the caller’s $status: both names refer to the same value. Writing through $st therefore changes $status, and the change is still visible after the function ends. Without &, the default is passing by value, so assigning to the parameter does not change the caller’s variable.

Put & before the parameter name in the declaration, not at the call site. Pass an initialized variable, as in markReady($status). The literal in markReady('Ready') is not a variable and causes an error. Do not pass ordinary expressions that compute a value either; the result of a function that returns by reference is a separate permitted case.

The string parameter type is checked on entry, not again on return. : void means the function returns no value; the effect is visible in the variable you passed. Use & when changing the caller’s variable is intentional, and document that behavior because the call itself does not show it.

Examples

<?php
function markReady(string &$st): void
{
    $st .= '!';
}

$status = 'Ready';
echo $status, "\n";
markReady($status);
echo $status, "\n";

Result

Ready
Ready!

The first line is `Ready`. The function appends `!` through `$st`, so the second line is `Ready!`. Remove only `&` from the declaration and both lines read `Ready`.

Related lessons

  • PHP · Lesson 34 · Intermediate · Version: 3

Sources