SoFunction
Updated on 2025-04-04

PHP Learning: Recognize the scope of functions of variables

Task 2: Recognize the scope of the variables

⚑ Local variables and global variables

The existence of a variable has its life cycle. We can make it exist within 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 using $globals are valid in the entire program on the current page.

example:
Copy the codeThe code is as follows:

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

In this program,
In lines 2 to 3, we create two variables a and b and assign them values ​​1 and 2 respectively.
From lines 3 to 7, we define a self-added function sum(), which is used to add variables a and b inside sum and assign the added value to b.
Line 8, call the sum function.
Line 9, use echo to output the value of b.
Some people may think that the value output on the web page must be 3 at this time, but after running, you will find that the value is still 2, which is the original value of b. This is the reason for local variables. The variables declared in lines 2 to 3 cannot be used in the sum() function. That is to say, the a and b used in the sum function and the a and b are just the same names, but there is no relationship between the two. Therefore, the final output b is the value of line b in line 3.

But if, we modify the following style to the program:
Copy the codeThe code is 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 add a global modifier to the variables a and b. At this time, a and b establish a relationship with a and b outside the function, and they are the same variable. Therefore, when this program is running, the result is 3. Therefore, when we declare global variables, we just need to add a modifier global when we use them locally (in this case, in the function sum), and they can inherit external values ​​and are no longer local variables.