PHP Function Call by Value Example

PHP Function Call by Value Example

  • PHP
  • 3 mins read

What is call by value?

In Call by value, we can pass the value directly to a function. The called function will contain the value in a local variable. Any modifications made to the parameter of the function definition will not affect the source variable. In this tutorial, I am giving an example of a PHP function call by value.

Here is a PHP Function Example for Implementing Call by Value Method

We are using a function here swap with arguments $a and $b and we are using two source variables (here $b1 and $b2). We are also passing two values directly to the function swap.

<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:-5 10

In this program, we are getting values of two source variables before calling the function as 5 and 10 and then after calling the function using call by value method as 5 and 10. Here there are some changes inside the function swap but those changes are not affecting on the source variables (here $b1 and $b2).

Here is another program for implementation call by value in PHP

This program is using call by value method. Here we are passing the value directly to the function f1. Here $b is an actual variable, and the value of the actual variable will not be changed after calling the function. Because in the call by value method, if there are any changes inside the function, will not affect the source value here $b.

<html>
    <body>
        <?php
function f1($a) // $a is the formal parameter
{
    $a.="Year"; //some changes
}
$b="Happy new";
echo "Before calling the function f1:-"."<br>";
echo "The value of source variable is:-".$b."<br>";
f1($b);
echo "After calling the function f1:-"."<br>";
echo "The value of source variable is:-".$b;
        ?>
    </body>
</html>

Output

Before calling the function f1:-
The value of source variable is:-Happy new
After calling the function f1:-
The value of source variable is:-Happy new

For call by value method, in the above program, the value of source variable $b (here "Happy new")is not changing before and after calling the function.