PHP Implementation Method Example of Modifying External Variable Values in Functions

  • 2021-11-13 06:50:01
  • OfStack

In this paper, an example is given to describe the method of modifying the value of external variables in PHP. Share it for your reference, as follows:

Go directly to the code, as follows:


$a_str = 'ab';
function change_val(){
  global $a_str; //  Modify variable values by setting global variables 
  //$a_str = 'abc';
  $a_str = $a_str.'abc';
}
echo $a_str."<br>";
change_val();
echo $a_str."<br>";
echo str_repeat('#',20)."<br>";
$b_str = 'ab';
function change_val_1($s){
  $s = 'abc';
  //$s = $s.'abc';
  return $s; //  Modify the variable value by returning the value 
}
echo $b_str."<br>";
$b_str = change_val_1($b_str);
echo $b_str."<br>";
echo str_repeat('#',20)."<br>";
$c_str = 'ab';
function change_val_2(&$c_str){// Reference call 
  //$c_str = 'abc';
  $c_str = $c_str.'abc';
}
echo $c_str."<br>";
change_val_2($c_str);
echo $c_str."<br>";

Run results:

ab
ababc
####################
ab
abc
####################
ab
ababc

Summary:

Use global variables as little as possible. Global variables increase memory usage. A value-passing call will create a copy, which will affect performance when the amount of data is large. When the reference is called, the function receives the variable address and does not create a copy of the data, which is efficient.

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of Common Functions and Skills of php", "Summary of Usage of php String (string)", "Tutorial of PHP Data Structure and Algorithm", "Summary of php Programming Algorithm" and "Complete Collection of Operation Skills of PHP Array (Array)"

I hope this article is helpful to everyone's PHP programming.


Related articles: