The scope of a variable is the context in which it is defined (that is, its effective scope). In JavaScript, there is no concept of variable scope, and it is likely that the scope is similar. However, since Javscript uses the lexical scope, which refers to the position of the variable declaration, there is no variable declaration in PHP, and the variable is the equivalent of declaring the variable at the first assignment. So, they are not the same. The scope of variables in PHP is described in detail in this article.
1. Local Variables
A local variable is a variable declared within a function whose scope is limited to the inside of the function. The parameter of a function is also a local variable, except that the value of the function parameter comes from the value passed in when it is invoked. The dynamic variables inside the function will be freed after execution is complete.
<?php function A ($b) { $c = 1; echo "$b + $c =". ($b + $c). ' <br/> '; } A (2);//Output 3 echo $b + $c;//illegal access outside the function, report notice error, and output 0?>
2. Global Variables
Variables defined outside the function are called global variables, scoped to the beginning of the definition variable to the end of the program file.
In addition, you cannot call global variables directly in a function, you need to use the keyword global, or you can use $globals instead of global. $GLOBALS is a super global variable.
<?php //Example 1 $a = 1; $b = 2; function Sum () { global $a, $b; $b = $a + $b; } Sum (); echo $b;//The result of the output is 3 //Example 2 $c = 1; $d = 2; function Sum () { $GLOBALS [' d '] = $GLOBALS [' C '] + $GLOBALS [' d ']; } Sum (); echo $d;//Output 3?>
3. Static variables
A static variable exists only in the local function domain, but its value is not lost when the program executes away from the scope. Static variables are declared with statics, and the default is a dynamic variable that is not declared by static. After the function has been executed, the internal static variables are already stored in memory. This function is initialized only the first time it is called during script execution.
<?php function Test () { static $a = 0; echo $a; $a + +; } Test ();//Output 0 test ();//Output 1?>
Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because they can be recursive indefinitely. You must ensure that there is sufficient method to abort the recursion. The following simple function recursively counts to 10, using a static variable $count to determine when to stop
<?php function Test () { static $count = 0; $count + +; echo $count; if ($count <) { test (); } $count--; }? >
Related recommendations:
PHP variable Range
PHP variable range, PHP global variables and static variables
PHP Variable Scope Introduction _php tutorial