PHP - Call by Reference

Welcome, aspiring programmers! Today, we're diving into an exciting topic in PHP: Call by Reference. Don't worry if you're new to programming; I'll guide you through this concept step by step, just as I've done for many students over my years of teaching. Let's embark on this coding adventure together!

PHP - Call by Reference

What is Call by Reference?

Before we jump into the nitty-gritty, let's understand what "Call by Reference" means. In PHP, when we pass a variable to a function, we typically pass its value. This is called "Call by Value." However, sometimes we want to pass the variable itself, not just its value. This is where "Call by Reference" comes in handy.

Imagine you have a box (variable) containing a toy (value). When you pass the box by value, you're giving someone a copy of the toy. But when you pass by reference, you're giving them the actual box itself. Any changes they make affect the original box and its contents.

Example

Let's start with a simple example to illustrate this concept:

<?php
function addFive($num) {
    $num += 5;
}

$myNumber = 10;
addFive($myNumber);
echo $myNumber; // Output: 10
?>

In this example, we're passing $myNumber by value. The function addFive() adds 5 to the parameter, but it doesn't affect the original $myNumber variable. The output remains 10.

Now, let's modify this to use call by reference:

<?php
function addFive(&$num) {
    $num += 5;
}

$myNumber = 10;
addFive($myNumber);
echo $myNumber; // Output: 15
?>

Notice the & before the parameter $num. This tells PHP to pass the variable by reference. Now, when we call addFive($myNumber), it modifies the original $myNumber, and the output is 15.

Calling a PHP Function by Reference

To call a function by reference, we need to do two things:

  1. Define the function parameter with an & before it.
  2. Pass a variable (not a value) when calling the function.

Here's another example:

<?php
function double(&$value) {
    $value *= 2;
}

$number = 5;
double($number);
echo $number; // Output: 10

$string = "Hello";
double($string);
echo $string; // Output: HelloHello
?>

In this example, our double() function works on both numbers and strings. It modifies the original variable in both cases.

Swapping Two Variables

One common use of call by reference is swapping the values of two variables. Let's see how we can do this:

<?php
function swap(&$a, &$b) {
    $temp = $a;
    $a = $b;
    $b = $temp;
}

$x = "lemonade";
$y = "iced tea";

echo "Before swap: x = $x, y = $y\n";
swap($x, $y);
echo "After swap: x = $x, y = $y\n";
?>

Output:

Before swap: x = lemonade, y = iced tea
After swap: x = iced tea, y = lemonade

This swap function is like a magician's trick - it makes two variables exchange their values! Without call by reference, we'd need to return multiple values or use global variables, which can get messy.

Return by Reference

PHP also allows functions to return a reference. This is less common but can be useful in certain scenarios. Here's an example:

<?php
function &getLargestNumber(&$numbers) {
    $largest = &$numbers[0];
    foreach ($numbers as &$number) {
        if ($number > $largest) {
            $largest = &$number;
        }
    }
    return $largest;
}

$myNumbers = [5, 8, 3, 12, 7];
$largestNumber = &getLargestNumber($myNumbers);
$largestNumber = 100;

print_r($myNumbers);
?>

Output:

Array
(
    [0] => 5
    [1] => 100
    [2] => 3
    [3] => 12
    [4] => 7
)

In this example, getLargestNumber() returns a reference to the largest number in the array. When we modify $largestNumber, it actually changes the value in the original array.

Methods Table

Here's a table summarizing the methods we've discussed:

Method Syntax Description
Pass by Reference function myFunc(&$param) Allows a function to modify the original variable
Return by Reference function &myFunc() Returns a reference instead of a value
Swap Variables swap(&$a, &$b) Exchanges the values of two variables

Conclusion

Call by Reference in PHP is like giving someone the keys to your house instead of just a picture of it. It's powerful but should be used judiciously. Remember, with great power comes great responsibility!

As you continue your PHP journey, you'll find many more exciting concepts to explore. Keep coding, keep learning, and most importantly, have fun! Who knows, maybe one day you'll be the one teaching others about the magic of programming.

Credits: Image by storyset