Open In App
Related Articles

How to pass PHP Variables by reference ?

Improve Article
Improve
Save Article
Save
Like Article
Like

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 geeksforgeeks"."\n";
  
    // Print $string variable
    print($string);
}
  
// Driver code
$string = "Global geeksforgeeks"."\n";
print_string($string);
print($string);
?>


Output:

Function geeksforgeeks
Global geeksforgeeks

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 geeksforgeeks \n";
  
    // Print $string variable
    print( $string );
}
  
// Driver code
$string = "Global geeksforgeeks \n";
print_string( $string );
print( $string );
?>


Output:

Function geeksforgeeks 
Function geeksforgeeks

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 20 Dec, 2018
Like Article
Save Article
Similar Reads
Related Tutorials