Home >Backend Development >PHP Tutorial >PHP Task Learning 2: Recognize the Scope of Variables_PHP Tutorial
Local variables and global variables
The existence of a variable has its life cycle. We can let it exist inside a small function, or we can let it exist in the entire program. For variables declared under normal circumstances, we call them local variables, which can only exist in the current program segment, while variables declared using $globals will be valid throughout the entire program on the current page.
Example:
Copy to ClipboardQuoted content: [www.bkjia.com]
<?php <br /> $a=1;<br> $b=2;<br> function sum()<br> {$a;<br> $b;<br> $b=$a+$b;<br> }<br> sum();<br> echo$b;<br> ?>
During this process,
In lines 2 to 3, we create two variables a and b and assign them the values 1 and 2 respectively.
From lines 3 to 7, we define a self-adding function sum(), which adds the variables a and b inside sum and assigns the added value to b.
Line 8 calls the sum function.
Line 9 uses echo to output the value of b.
Some people may think that the value output on the web page at this time must be 3, but after running it, you will find that the value is still 2, which is the original value of b. This is caused by local variables. The variables declared in lines 2 to 3 cannot be used in the sum() function. That is to say, a and b used in the sum function are not the same as a and b in lines 2 to 3. They just have the same name, but they have nothing to do with each other. Therefore, the b in the final output is the value of b in line 3.
But if, we will modify the program to the following style:
Copy to ClipboardQuoted content: [www.bkjia.com]
<?php <?php<br /> $a=1;<br> $b=2;<br> function sum()<br> {<br> global $a,$b;<br> $b=$a+$b;<br> }<br> sum();<br> echo $b;<br> ?><br> <pre class="brush:php;toolbar:false"><br> <BR><BR>
We found that in the sum function, we added a global modifier to the variables a and b. At this time, a and b have established a relationship with a and b outside the function, and they are the same variable. Therefore, when this program is run, the result is 3. Therefore, when we declare global variables, we only need to add a modifier global to them when using them locally (in this case, in the function sum), so that they can inherit external values and are no longer local. variable.