PHP variables passed by reference

The & symbol &is added to the beginning of the variable parameters to allow variables to be passed by reference in PHP. For example, function(&$a), where the variable targets of global and function both become global values ​​because they are defined using the same reference concept.

Whenever a global variable changes, the variables inside the function also change, and vice versa. The syntax for passing by reference is:

function FunctionName(&$Parameter){
    
    
//
}

where FunctionNameis the name of the function and Parameteris a variable that will be passed by reference. This is a simple example of passing by reference in PHP.

<?php
function Show_Number(&$Demo){
    
    
    $Demo++;
}
$Demo=7;
echo "Value of Demo variable before the function call :: ";
echo $Demo;
echo "<br>";
echo "Value of Demo variable after the function call :: ";
Show_Number($Demo);
echo $Demo;
?>

The above code Show_Numberpasses the variable by reference in the function Demo. See output:

Value of Demo variable before the function call :: 7
Value of Demo variable after the function call :: 8

Let's try another example to pass by reference with and without the ampersand. See example:

<?php
// Assigning the new value to some $Demo1 variable and then printing it
echo "PHP pass by reference concept :: ";
echo "<hr>";
function PrintDemo1( &$Demo1 ) {
    
    
    $Demo1 = "New Value \n";
    // Print $Demo1 variable
    print( $Demo1 );
    echo "<br>";
}
// Drivers code
$Demo1 = "Old Value \n";
PrintDemo1( $Demo1 );
print( $Demo1 );
echo "<br><br><br>";


echo "PHP pass by reference concept but exempted ampersand symbol :: ";
echo "<hr>";
function PrintDemo2( $Demo2 ) {
    
    
    $Demo2 = "New Value \n";
    // Print $Demo2 variable
    print( $Demo2 );
    echo "<br>";
}
// Drivers code
$Demo2 = "Old Value \n";
PrintDemo2( $Demo2 );
print( $Demo2 );
echo "<br>";

?>

The code above creates two functions that change the value of a variable. When a variable &is passed by reference to the symbol, the function is called at the same time and changes the value of the variable.

Similarly, when passed by reference without the ampersand, it requires calling a function to change the value of the variable. See output:

PHP pass by reference concept ::
New Value
New Value


PHP pass by reference concept but exempted ampersand symbol ::
New Value
Old Value

Guess you like

Origin blog.csdn.net/weixin_50251467/article/details/131777530