Home > Backend Development > PHP Tutorial > photoshop learning php learning to recognize the scope of variables

photoshop learning php learning to recognize the scope of variables

WBOY
Release: 2016-07-29 08:41:45
Original
953 people have browsed it

Task 2: Recognize the scope of variables
⚑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 code The code is as follows:


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


In this program,
line 2 to 3, we create two variables a and b and give them respectively Its assigned values ​​are 1 and 2.
In lines 3 to 7, we define a self-adding function sum(), whose function is to add the 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 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 modify the program to the following style:

Copy the code 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 add variables a and b With a global modifier, a and b are related to 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.

The above introduces how to understand the scope of variables in photoshop learning and php learning, including the content of photoshop learning. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template