PHP Function Call by Reference Example

PHP Function Call by Reference Example

  • PHP
  • 3 mins read

What is call by reference in PHP?

In call by reference, we will pass the address of a variable where the actual value is stored. The called function will use the value stored in the given address. In this process, the real value will be changed if it is modified inside the function. In call by reference, we will use a symbol & with formal parameters and $ will specify the reference of the variable.

Here is a PHP Function for using call by reference method:

In this program, we are using a variable $b which is passing to the function here f1 where it is concatenated with 'Year'. There is a changing in the actual variable $b.

<html>
    <body>
        <?php
function f1(&$a) // here $a is a formal parameter
{
    $a.="Year";
}
$b="Happy new ";
f1($b);
echo $b;
        ?>
    </body>
</html>

Output

Happy new Year

In this program, we are passing the address of a variable $a where the actual value is stored. Here actual value(here "Happy new ")is changing, because there is a modification inside the function and after the execution of the program we will get the value of $b("Happy New Year").

Here is another PHP program to swap the values of two numbers using call by reference method:

In this program, there is a user define function swap where we are passing the addresses of two formal parameters(here $a and $b)and two actual variables(here $b1 and $b2). Before calling the function, actual values will not be changed but after the calling the function swap, actual values will be changed. Because there are some changes here inside the function.

<html>
    <body>
        <?php
function swap(&$a,&$b)
{
    $c=$a;
    $a=$b;
    $b=$c;
}
$b1=5;
$b2=10;
echo "Before calling the function swap:-"."<br>";
echo "The two values are:-".$b1." ".$b2."<br>";
swap($b1,$b2);
echo "After calling the function swap:-"."<br>";
echo "The two values are:-".$b1." ".$b2."<br>";
        ?>
    </body>
</html>

Output

Before calling the function swap:-
The two values are:-5 10
After calling the function swap:-
The two values are:-10 5

In this program, call be reference is using, before calling the function swap, two actual values are 5 and 10. After calling the function, actual values are changing as 5 to 10 and 10 to 5.