Pass by Value and Pass by Reference Example in PHP

Hello php devs in this quick example i will discuss about reference variable in php with example. If you don't know pass by value and pass by reference in php then this example is for you.

If you know c or c++ then it should be common word to you that pass by value and pass by reference in any programming language. Normally in PHP By default, PHP variables are passed by value as a function arguments in PHP.

You know that when variables in PHP is passed by value, the scope of that variable defined at function which bound within the scope of function. Changing value of the variables doesn’t have any effect on either of the variables.

Example: Pass by Value in PHP

function print_string( $string ) { 
    $string = "I am mahedi!"; 
    print($string); 
} 
  
$string = "I am john doe";
print_string($string); 
print($string); 

 

Output:

 

OUTPUT
I am mahedi
I am john doe

 

Pass by reference in PHP:

You can pass a variable by reference to a function so the function can modify the variable. When a variables is passed by reference in PHP, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ).

Scope of both global and function variable becomes global as both variables are defined by same reference. Therefore, whenever global variable is change, variable inside function also gets changed and vice-versa.

Example:

function print_string( &$string ) { 
    $string = "I am mahedi!"; 
    print($string); 
} 
  
$string = "I am john doe";
print_string($string); 
print($string);

 

Output:

 

OUTPUT
I am mahedi
I am mahedi

 

Read also : Way to Access Private Property or Method In PHP

 

Hope this pass by value and pass by reference is now clear to you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.