Call by Value and Call by Reference in PHP

Difference between call by value and call by reference in PHP

Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.

Call by reference means passing the address of a variable where the actual value is stored. The called function uses the value stored in the passed address; any changes to it do affect the source variable.

Example

This is a "global", or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $x; to access it within functions or methods.

<?php

//Call by value program

function abc($x)

{

$x=$x+10;

return($x);

}

$a=20;

echo abc($a)."<br>";

echo ($a);

?>

Note: Call by value: in the call by value method, the called function creates a new set of variables and copies the values of arguments into them.

Output: 

Call by value program in php.jpg

<?php

//call by reference program in php

function abc($x)

{

$x=$x-10;

return($x);

}

$a=50;

echo abc($a)."<br>";

echo ($a);

?>

Note: Call by reference: in the call by reference method, instead of passing a value to the function being called a reference/pointer to the original variable is passed.

Output:

Call by reference program in php.jpg 

Up Next
    Ebook Download
    View all
    Learn
    View all