Passing Function Arguments in PHP : Call By Value and Call By Reference

PHP allows users to call function by value as well as call by reference.

Call by Value :

When we call a function by value then actual value which is supplied to function as argument is not modified, instead the php make a copy of that value and used that copied value inside the function and when the function exits then it will delete that copy version of the value. Now lets see an example :
<?php
  function modify($num) {
    $num += 10;
    echo "Value of supplied Argument inside Function : $num <br/><br/>";
  }

  $x = 20;
  echo "Before function call, Value of \$x is : $x <br/><br/>";
  modify($x);
  echo "After function call, Value of \$x is : $x";
?>
Output :

Before function call, Value of $x is : 20

Value of supplied Argument inside Function : 30

After function call, Value of $x is : 20

At the above example the value of $x is 20 before function call, and inside the function 10 is added to the value of $x. And after the function call the value of $x is still 20, it is not changed or modified.


Call by Reference :

When we call a function by reference then the actual value of supplied argument is modified within the function. In the call by reference we need to to use the & ( ampersand ) symbol with formal arguments. The & represents the reference of the variable. Lets see an example :
<?php
  function modify(&$num) {
    $num += 10;
    echo "Value of supplied Argument inside Function : $num <br/><br/>";
  }

  $x = 20;
  echo "Before function call, Value of \$x is : $x <br/><br/>";
  modify($x);
  echo "After function call, Value of \$x is : $x";
?>
Output :

Before function call, Value of $x is : 20

Value of supplied Argument inside Function : 30

After function call, Value of $x is : 30

As we can see in the above example the value of $x is changed by calling the function. Now lets see another example :
<?php
  function inc(&$num) {
    $num++;
  }

  $x = 5;
  inc($x);
  echo $x . "<br/>";

  $y = 10;
  inc($y);
  echo $y . "<br/>";
?>
Output :

6
11

At above functions the variable $x and $y values are incremented by 1.


Next Topic :