Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Parameters passed by reference

Pass-by-reference parameters put the ampersand in the declaration and bind the parameter to an argument variable.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

function bump(int &$value): void { ++$value; }

Pass-by-reference parameters put the ampersand in the declaration and bind the parameter to an argument variable. Assignment inside the function updates the caller’s variable without a return value. An array element can be supplied as a writable variable, whereas a literal cannot and raises Error. The call site uses ordinary argument syntax without an ampersand.

function bump(int &$value): void { ++$value; }
$n = 2; $rows = [5];
bump($n); bump($rows[0]);
echo json_encode([$n, $rows]), PHP_EOL;
try { bump(2); } catch (Error $e) { echo get_class($e); }
[3,[6]]
Error

Examples

<?php
function bump(int &$value): void { ++$value; }
$n = 2; $rows = [5];
bump($n); bump($rows[0]);
echo json_encode([$n, $rows]), PHP_EOL;
try { bump(2); } catch (Error $e) { echo get_class($e); }

Result

[3,[6]]
Error

Sources