Call by Value & Call by Reference in PHP with Example

What’s the difference between call by value & call by reference in PHP? This is the most important concept used in programming and sometime asked in interviews. Don’t worry if you are new to this terminology, you’ll learn this concept in this tutorial.

Call by value & call by reference in PHP

Call by value & call by reference in PHP

Call by Value & Call by Reference in PHP

Example 1: Let’s understand this concept using some programming examples.

Example 2: Now again write this script with minimal modification in an argument.

We have seen the examples and their differences in output. Let’s understand what exactly is call by value & call by reference.

PHP MCQ for practice

Call by Value in PHP

In call by value, the value of a variable is passed directly. It means, if the value of a variable within the function is changed, it doesn’t get changed outside of the function. As we seen in our first example.

Call by Reference in PHP

In call by reference, the address of a variable (their memory location) is passed. In the case of call by reference, we prepend an ampersand (&) to the argument name in the function definition. Any change in variable value within a function can reflect the change in the original value of a variable which we have seen in our second example.
Magic methods in PHP

Swap Two Numbers using Call By Value in PHP

In call by value, the actual value of a variable is passed. In this example, we have swap two numbers using call by value.

Swap two numbers in PHP

PHP code – Find first non-repeated character in a string

Swap Two Numbers using Call By Reference in PHP

In call by reference,  Address of a variable is passed.  Address represents where the value of a variable is stored. In this example, we swap two numbers using call by reference in PHP.

How to sort a string in PHP

In the above example, we have passed the value of $a = 5 and $b = 7 in swap() method. In swap() method, we are passing the value by reference. It means the address of a variable is passed. So any change in the value of variables in a swap() will reflect them in original values of a variable.

PHP 7 features

For further you can check PHP documentation.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.