Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Reference parameter `&$value` versus passing by value

In PHP 8.3, a parameter declared as `&$value` lets the function change the caller’s variable. With the default pass by value, assigning to the parameter does not change that variable.

Version: PHP 8.3; extension availability may vary

Syntax

function addOneByReference(int &$value): void { $value += 1; }
$number = 5;
addOneByReference($number);

A reference parameter &$value makes the local parameter an alias for the caller’s variable. In int &$value, & marks the parameter as by-reference; it does not create a C-style pointer. Writing through $value updates the shared value, and returning from the function does not undo the update.

Put & in the declaration, not at the call site: addOneByReference($number). Pass a variable or the result of a function explicitly declared to return by reference. A literal such as 5 causes an error, and ordinary expressions such as $number + 1 are not valid arguments here. An & before a function name declares a reference return, not a reference parameter.

Without &, the default is pass by value: assigning to $value stays local. When the argument is an object, both variables can still identify the same object. Changing its properties can therefore be visible to the caller, but assigning a different object to the parameter does not change the caller’s variable.

For int &$value, the parameter type is checked on entry, not on return. The declaration alone does not guarantee that an ordinary caller variable will still be an int afterward. Use & when changing the caller’s variable is part of the function’s contract, and document that side effect. Otherwise, consider returning the new value.

Examples

<?php
declare(strict_types=1);

function addOneByValue(int $value): void
{
    $value += 1;
}

function addOneByReference(int &$value): void
{
    $value += 1;
}

$number = 5;
addOneByValue($number);
echo "by value: $number\n";

addOneByReference($number);
echo "by reference: $number\n";

Result

by value: 5
by reference: 6

Both functions run `$value += 1`. After the by-value call, `$number` is still `5`; after the by-reference call, it is `6`.

Related lessons

  • PHP · Lesson 77 · Advanced · Version: 2

Sources