PHP Pass by Value vs Pass by Reference

When writing functions in PHP, understanding how arguments are passed is crucial for managing memory and avoiding unexpected bugs. This article explains the core differences between passing arguments by value and by reference, demonstrates how each method affects your variables, and provides clear examples to help you choose the right approach for your code.

Passing by Value (Default Behavior)

By default, PHP passes arguments by value. When you pass a variable to a function by value, PHP creates a copy of the variable’s original value and sends that copy to the function. Any modifications made to the variable inside the function only affect the local copy, leaving the original variable outside the function unchanged.

Here is an example of passing by value:

function addFive($number) {
    $number += 5;
    return $number;
}

$originalValue = 10;
$newValue = addFive($originalValue);

echo $originalValue; // Outputs: 10
echo $newValue;      // Outputs: 15

In this example, $originalValue remains 10 because the function addFive only modified a copy of the variable.

Passing by Reference

When you pass an argument by reference, you are passing the actual memory address of the original variable to the function, rather than a copy. To do this, you must prepend an ampersand (&) to the parameter name in the function definition.

Any changes made to the parameter inside the function will directly modify the original variable.

Here is an example of passing by reference:

function addFiveByReference(&$number) {
    $number += 5;
}

$originalValue = 10;
addFiveByReference($originalValue);

echo $originalValue; // Outputs: 15

Because the function received a reference to $originalValue, the addition operation modified the original variable directly. Note that the function does not need to return a value to update the variable.

Key Differences

Feature Pass by Value Pass by Reference
Syntax function myFunction($var) function myFunction(&$var)
Data Handling Operates on a copy of the data. Operates on the original data.
Original Variable Remains unchanged outside the function. Changes permanently if modified in the function.
Use Case Standard calculations, read-only data, safety. Modifying large datasets in place, returning multiple values.

A Note on PHP Objects

It is important to note that in PHP, objects are passed by reference-like behavior by default. When you pass an object to a function, PHP passes a copy of the object identifier (or handle), which still points to the same underlying object. Therefore, modifying the properties of an object inside a function will affect the original object, even without using the & symbol.