• Tutorial List

What is PHP function Pass By Value and Pass By Reference?

Last updated May 15, 2020
What is PHP function Pass By Value and Pass By Reference?

PHP function Pass By Value

By default, PHP variables are passed by value as function arguments in PHP.

That means when you pass a variable as the function argument and modify this argument it does not affect the original variable.

<?php
  $num = 12;
  function myFunc($arg){
      // changing the argument value
      $arg = 7;
      echo "Inside Function - $arg";
  }
  myFunc($num);
  echo "<br>";
  echo "Original Variable - $num";
?>
Browser Output
Inside Function – 7
Original Variable – 12

PHP function Pass by Reference

Pass by reference is the inverse of the pass by value, that means when you modify the function argument it will affect the original variable.

The “&” Is used to activate pass by reference.

<?php
  $num = 12;
  function myFunc(&$arg){
      // changing the argument value
      $arg = 7;
      echo "Inside Function - $arg";
  }
  myFunc($num);
  echo "<br>";
  echo "Original Variable - $num";
?>
Browser Output
Inside Function – 7
Original Variable – 7