Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Returning by reference

Returning by reference places & before the function name and returns a variable that a caller can alias using =&.

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

Syntax

function &slot(array &$items, int $key): mixed { return $items[$key]; }

Returning by reference places & before the function name and returns a variable that a caller can alias using =&. A plain assignment receives the value without forming the requested alias. Return a writable variable such as a property or array element rather than a computed expression. In the example only the explicitly bound result changes the original array.

function &slot(array &$items, int $key): mixed { return $items[$key]; }
$items = [4];
$copy = slot($items, 0);
$ref =& slot($items, 0);
$copy = 8; $ref = 12;
echo json_encode([$items, $copy]);
[[12],8]

Examples

<?php
function &slot(array &$items, int $key): mixed { return $items[$key]; }
$items = [4];
$copy = slot($items, 0);
$ref =& slot($items, 0);
$copy = 8; $ref = 12;
echo json_encode([$items, $copy]);

Result

[[12],8]

Sources