Home » PHP Call by Reference : A Tutorial with Examples

PHP Call by Reference : A Tutorial with Examples

In PHP, you can pass function arguments by reference, allowing the function to modify the original variable’s value. When using call by reference, instead of passing a copy of the variable, PHP passes a reference to the original variable.

This means that changes made to the parameter inside the function will directly affect the original variable.

In this tutorial, we will cover:

Let’s explore each of these topics with examples and explanations.

1. What is Call by Reference?

Call by reference is a method of passing arguments to a function where the function receives a reference (or address) to the original variable. This allows the function to modify the original variable’s value directly. To pass a variable by reference in PHP, you use the & operator.

Syntax:

function functionName(&$parameter) {
    // Function body
}
  • The & symbol before the parameter indicates that it is passed by reference, meaning any changes to the parameter inside the function will be reflected in the original variable.

2. How Call by Reference Works in PHP

When a variable is passed by reference, PHP passes a pointer to the original variable, allowing the function to modify the original variable directly.

Example (Basic Call by Reference):

<?php
// Function that modifies a variable by reference
function addTen(&$number) {
    $number += 10;
}

// Original variable
$value = 20;

// Call the function, passing the variable by reference
addTen($value);

// Print the updated value
echo "Updated value: $value\n";  // Outputs: Updated value: 30
?>
  • In this example, the function addTen() modifies the original value of $value by passing it by reference. As a result, $value is updated to 30 after the function call.

3. Examples of Call by Reference

Let’s explore more examples to see how call by reference works with different data types and scenarios.

Example (Call by Reference with Arrays):

<?php
// Function that adds an item to an array by reference
function addItemToArray(&$arr, $item) {
    $arr[] = $item;
}

// Original array
$array = ["Apple", "Banana"];

// Call the function, passing the array by reference
addItemToArray($array, "Orange");

// Print the updated array
print_r($array);
?>

Output:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Orange
)
  • In this example, the array $array is passed by reference to the addItemToArray() function. The function appends “Orange” to the array, and the original array is updated.

Example (Call by Reference with Multiple Variables):

<?php
// Function that increments two numbers by reference
function incrementBoth(&$a, &$b) {
    $a++;
    $b++;
}

// Original values
$num1 = 5;
$num2 = 10;

// Call the function, passing both variables by reference
incrementBoth($num1, $num2);

// Print the updated values
echo "num1: $num1, num2: $num2\n";  // Outputs: num1: 6, num2: 11
?>
  • In this example, both $num1 and $num2 are passed by reference to the incrementBoth() function. The function increments both values, and the changes are reflected in the original variables.

4. Difference Between Call by Value and Call by Reference

The key difference between call by value and call by reference lies in how the arguments are passed and whether the original variable can be modified.

Call by Value:

  • The function receives a copy of the argument’s value.
  • Modifications inside the function do not affect the original variable.
  • Default behavior in PHP.

Call by Reference:

  • The function receives a reference (or pointer) to the original variable.
  • Modifications inside the function affect the original variable.
  • Achieved using the & operator.

Example (Call by Value vs. Call by Reference):

<?php
// Function using call by value (default behavior)
function multiplyByTwo($num) {
    $num *= 2;
}

// Function using call by reference
function multiplyByTwoRef(&$num) {
    $num *= 2;
}

$value = 5;
$valueRef = 5;

multiplyByTwo($value);        // Call by value
multiplyByTwoRef($valueRef);  // Call by reference

echo "Call by value result: $value\n";      // Outputs: Call by value result: 5
echo "Call by reference result: $valueRef\n";  // Outputs: Call by reference result: 10
?>
  • In this example, the multiplyByTwo() function (call by value) does not affect the original $value, while the multiplyByTwoRef() function (call by reference) modifies the original $valueRef.

5. Use Cases for Call by Reference

Modifying the Original Variable

Call by reference is useful when you want a function to directly modify the original variable passed to it. This is common in scenarios like:

  • Updating arrays or objects within a function.
  • Swapping variables.
  • Optimizing performance by avoiding the creation of large copies of variables, especially with arrays or objects.

Example (Using Call by Reference to Update a Variable):

<?php
// Function to set a value by reference
function setToHundred(&$num) {
    $num = 100;
}

$myNumber = 50;

// Call the function to modify the variable
setToHundred($myNumber);

// Print the updated value
echo "Updated value: $myNumber\n";  // Outputs: Updated value: 100
?>
  • In this example, the setToHundred() function sets the original variable $myNumber to 100 using call by reference.

6. Example: Swapping Two Variables Using Call by Reference

One common use case for call by reference is to swap the values of two variables. This can be done efficiently without creating temporary copies of the variables.

Example (Swapping Variables with Call by Reference):

<?php
// Function to swap two variables by reference
function swap(&$x, &$y) {
    $temp = $x;
    $x = $y;
    $y = $temp;
}

$a = 10;
$b = 20;

// Call the swap function
swap($a, $b);

// Print the swapped values
echo "After swap: a = $a, b = $b\n";  // Outputs: After swap: a = 20, b = 10
?>
  • In this example, the swap() function swaps the values of $a and $b using call by reference. After the function call, the values of $a and $b are swapped without needing to return any values.

Summary of PHP Call by Reference:

Concept Description
Call by Reference Passing a reference to the original variable, allowing the function to modify it.
Syntax Use the & symbol before the parameter to indicate call by reference.
Impact on Original Variable The original variable is directly modified by the function.
Difference from Call by Value Call by value passes a copy of the variable, while call by reference passes the variable itself.
Use Cases Modifying original variables, updating arrays, swapping variables, avoiding large copies.

Conclusion

Call by reference in PHP allows you to pass variables to functions in a way that allows the function to modify the original variable. This is achieved using the & operator, which passes a reference to the variable instead of a copy. In this tutorial, we covered:

  • What call by reference is and how it works in PHP.
  • Examples of modifying variables and arrays using call by reference.
  • The difference between call by value and call by reference.
  • Common use cases for call by reference, such as swapping variables and optimizing performance.

You may also like