Task 2: Recognize the scope of variables
⚑ local variables and global variables
The existence of a variable has its lifecycle, and we can make it exist within a small function, or it can exist throughout the program. For variables declared in general, we call them local variables, which can only exist in the current program segment, whereas variables declared using $globals are valid throughout the current page.
Cases:
Copy Code code as follows:
<?php
$a = 1;
$b = 2;
function sum ()
{$a;
$b;
$b = $a + $b;
}
SUM ();
echo$b;
?>
In this procedure,
Line 2nd to 3rd, we created two variables A and B and assigned them 1 and 2, respectively.
Lines 3rd through 7th, we define a function sum (), which is to add the variables a and b within sum and assign the added value to B.
Line 8th, call the SUM function.
Line 9th, use echo to output the value of B.
One might think that the value of the output on a Web page at this point must be 3, but after running, you'll find that the value is still 2, which is the original value of B. This is the cause of the local variable, and the variable declared in the 2nd to 3rd business cannot be used in the sum () function, which means that A and B in line A and B and 2nd to 3rd of the SUM function have the same name, but there is no relationship between them. So, the value of B in the final output is the 3rd line B.
If, however, we modify the following style for the program:
Copy Code code as follows:
<?php
$a = 1;
$b = 2;
function sum ()
{
Global $a, $b;
$b = $a + $b;
}
SUM ();
Echo $b;
?>
We found that in the SUM function we added a global modifier to variables A and B, at which point A and B were related to A and B outside the function, and they were the same variable. Therefore, when the program is running, the result is 3. So when we declare global variables, we simply use them locally (in this case, in the sum of functions), add a modifier global, they can inherit external values, and they are no longer local variables.