The existence of a variable has its life cycle. we can make it exist in a small function or the whole program. Variables declared in general are called local variables and can only exist in the current program segment. variables declared using $ globals are valid throughout the program on the current page. Task 2: identify the scope of the variable
⚑Local variables and global variables
The existence of a variable has its life cycle. we can make it exist in a small function or the whole program. Variables declared in general are called local variables and can only exist in the current program segment. variables declared using $ globals are valid throughout the program on the current page.
Example:
The code is as follows:
$ A = 1;
$ B = 2;
Function sum ()
{$;
$ B;
$ B = $ a + $ B;
}
Sum ();
Echo $ B;
?>
In this program,
In rows 2nd to 3, we create two variables a and B and assign them 1 and 2 respectively.
Rows 3rd to 7th define a self-added function sum (). The function is to add the variables a and B in sum and assign the value to B.
Line 3 calls the sum function.
Line 2: use echo to output the value of B.
Some people may think that the output value on the webpage must be 3 at this time, but after running, you will find that the value is still 2, that is, the original value of B. This is because of local variables. variables declared in rows 2nd to 3 cannot be used in the sum () function, that is, in the sum function, the names of a and B are the same, but there is no relationship between them. Therefore, the value of B in the final output is the value of B in the 3rd rows.
However, if we modify the following style:
The code is as follows:
$ 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 this time, a and B have a relationship with a and B outside the function, they are the same variables. Therefore, when the program is running, the result is 3. Therefore, when declaring global variables, we only need to add a modifier global to them when using them locally (in this example, in the sum function, they can inherit external values, so they are no longer local variables.