PHP has four different variable scopes: static, parameter, global, local.
1. Global variables
are in All variables defined outside the function have global scope, and variables declared inside the function are local variables and can only be accessed within the function. To use global variables in a function, use the global keyword.
<?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); ?>
The second way to access variables in the global scope is to use a special PHP custom $GLOBALS array. The previous example can be written as:
<?php $a = 1; $b = 2; function Sum() { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum(); ?>
2. Static variable
Another important feature of variable scope is static variable (staticvariable). Static variables only exist in the local function scope, but their values are not lost when program execution leaves this scope.
Static variables defined in a function cannot be called outside the function.
Static variables also provide a way to deal with recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, as they may recurse indefinitely. You must ensure that there are adequate means to terminate recursion.
<?php function Test() { static $count = 0; $count++; echo $count; if ($count < 10) { Test (); } $count--; } ?>
3. Local variables
Parameters are local variables that pass values to the function through the calling code.
Sometimes it is very convenient to use variable variable names. That is, the variable name of a variable can be set and used dynamically. An ordinary variable is set by declaration, for example:
<span style="color:#000000;">##<?php<span style="color:#0000BB;">$a <br/></span> = <span style="color:#007700;"></span>"hello"<span style="color:#DD0000;"></span>;<span style="color:#007700;"></span>?><span style="color:#0000BB;"></span></span> |
uses two dollar signs ($), and it can be used as a variable variable. For example:
##<span style="color:#000000;">$<span style="color:#0000BB;"></span>$a <span style="color:#007700;"></span>= <span style="color:#0000BB;"></span>"world"<span style="color:#007700;"></span>;<span style="color:#DD0000;"></span>?><span style="color:#007700;"></span><span style="color:#0000BB;"></span></span> | # #At this time, both variables are defined: the content of
is "world". Therefore, it can be expressed as:
echo <span style="color:#000000;">"$a ${$a}"<span style="color:#0000BB;"></span>;<span style="color:#007700;"></span>?><span style="color:#DD0000;"></span><span style="color:#007700;"></span><span style="color:#0000BB;"></span></span> The following way of writing is more accurate And the same result will be output: |
"$ a $hello";?> |