PHP program to demonstrate the call by reference parameter passing

Here, we are going to demonstrate the call by reference parameter passing in PHP.
Submitted by Nidhi, on November 19, 2020

Here, we will pass parameters using call by reference mechanism to the user-defined function. In the call by reference parameter passing, the updated value of parameters also reflects in the calling function.

Program/Source Code:

The source code to demonstrate the call by reference parameter passing is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate call by 
//reference parameter passing
function Sum($num1, $num2, &$num3)
{
    $num3 = $num1 + $num2;

    echo "Inside function->num3: " . $num3 . "<br>";
}

$num1 = 10;
$num2 = 20;
$num3 = 0;

Sum($num1, $num2, $num3);
echo "Outside function->num3: " . $num3;
?>

Output:

Inside function->num3: 30
Outside function->num3: 30

Explanation:

In the above program, we created a function Sum() that accepts two arguments $num1 and $num2 as call by value and 3rd argument $num3 as a call by reference, here we used & to specify argument is passed as a reference.

In the Sum() function, we calculated the addition of $num1 and $num2 and assigned the result to the $num3. Here, we printed the value of $num3 inside the function, it will print the sum of $num1 and $num2 on the webpage.

After that we created three variables $num1, $num2, and $num3 that are initialized with 10, 20, and 30 respectively. Then we called the Sum() method and printed the value of $num3, and it will print 30 because here we passed the parameters as call by reference mechanism. And we know that in the call by reference parameter passing, the updated value of parameters also reflects in the calling function.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.