Thursday, September 4, 2025
HomeLanguagesHow to pass PHP Variables by reference ?

How to pass PHP Variables by reference ?

By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn’t have any effect on either of the variables.

Example:




<?php
  
// Function used for assigning new
// value to $string variable and 
// printing it
function print_string( $string ) {
    $string = "Function neveropen"."\n";
  
    // Print $string variable
    print($string);
}
  
// Driver code
$string = "Global neveropen"."\n";
print_string($string);
print($string);
?>


Output:

Function neveropen
Global neveropen

Pass by reference: When variables are passed by reference, 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 is applicable.

Example:




<?php
  
// Function used for assigning new value to 
// $string variable and printing it
function print_string( &$string ) {
      
    $string = "Function neveropen \n";
  
    // Print $string variable
    print( $string );
}
  
// Driver code
$string = "Global neveropen \n";
print_string( $string );
print( $string );
?>


Output:

Function neveropen 
Function neveropen
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS