Online Snippets Library

Call by Value & Call by Reference in PHP With Example

In this section of tutorial We will learn about,What is the difference between Call by Value & Call by Reference in PHP?.

Call By Value in PHP

Call By Value does not allow us to modified it's actual value if it is modified inside the function.

Let's understand It by an Example

<?php
function increment_by_value($number)
{
 $number = $number + 1;
 echo $number."\n";
}
$num = 1;
increment_by_value($num)."\n";
echo $num; 
?>

Out Put

1 1

As we seen in example.if the value of a variable within the function is modified, it doesn’t get changed outside of the function.

Call By Reference in PHP

Call By Reference does allow us to modified it's actual value if it is modified inside the function.In this case "&" (ampersand) symbol is used with formal arguments.

Let's understand It by an Example

<?php
function increment_by_ref(&$number)
{
 $number = $number + 1;
 echo $number."\n";
}
$num = 1;
increment_by_ref($num)."\n";
echo $num; 
?>