Tutorialspoint

1 Answer
Alok Prasad

In this article, we will learn about pass by value and pass by reference in PHP. 

Now, let’s understand these two concepts in detail.

In PHP generally, we followed to pass the arguments to the function with passed by value approach. We are following this practice because if the value of the argument within the function is changed, it does not get changed outside of the function.

In some cases we may need to modify function arguments, So to allow a function to modify its arguments, they must be passed by reference.

Let's begin with passed by reference. As it is already mentioned we can pass a variable by reference to a function so the function can modify the variable. To begin the process of passing the parameters passed by reference, prepend an ampersand (&) to the argument name in the function definition.

Let's test this with a simple example.

Example:

<?php
   function calculate(&$a){
      $a++;
   }
   $a=5;
   calculate($a);
   echo $a;
?>

Output:

6

Explanation:

Here we have declared variable $a and passing it as pass by reference to the function calculate(). So as the principle says if the value of the $a gets changed inside the function then it will be also going to change outside the function.

Note:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. This is deprecated in 5.4 version of PHP when you use to calculate(&$a); it throws an error.

Let's test an example to understand pass by value.

<?php
   function calculate($a){
      $a++;
   echo $a."<br/>";
   }
   $a=5;
   calculate($a);
   echo $a;
?>

Output:

6
5

Explanation:

Here we have passed the value to the function calculate() as pass by value. Its value gets changed inside the function but that is not reflected outside the function. The value of the variable remains the same outside the function.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.