PHP learning to recognize the scope of variables

  • 2020-03-31 20:15:38
  • OfStack

Task 2: recognize the scope of variables

The & # 9873; Local and global variables

The existence of a variable has a lifetime, and we can make it exist in a small function or in the entire program. For variables declared in general, we call them local variables, which can only exist in the current program segment, while variables declared with $globals are valid in the current page throughout the program.

Ex. :
 
<?php 
$a=1; 
$b=2; 
function sum() 
{$a; 
$b; 
$b=$a+$b; 
} 
sum(); 
echo$b; 
?> 

In this process,
In lines 2 to 3, we set up two variables a and b and assign them to 1 and 2, respectively.
Lines 3 through 7, we define a self-additive function, sum(), that adds the variables a and b inside sum and assigns the value to b.
Line 8, call the sum function.
Line 9, echo out the value of b.
One might think that the output on the web page at this point must be 3, but when you run it, it's still 2, which is the original value of b. That's why the local variables, the variables declared in lines 2 and 3 cannot be used in the sum() function, that is, the a and b used in the sum function are the same names as the a and b used in lines 2 and 3, but they have nothing to do with each other. So the final output b is going to be the value of b in line 3.

But if we change the program to the following style:
 
<?php 
$a=1; 
$b=2; 
function sum() 
{ 
global $a,$b; 
$b=$a+$b; 
} 
sum(); 
echo $b; 
?> 

And what we found is that in the sum function, we put a global modifier on the variables a and b, and at that point, a and b are related to a and b outside of the function, and they're the same variable. Therefore, when the program runs, the result will be 3. Therefore, when we declare global variables, we can simply use them locally (in this case, in the function sum), add a modifier global to them, and they will inherit external values, and they will no longer be local variables.

Related articles: