Home > Article > Backend Development > PHP four variable scope comparison
PHP is a relatively loose language (Loosely Typed Language). When we declare a variable, we do not need to specify the type of the variable (type). PHP will automatically use the value assigned to the variable. to determine the type of the variable. Although you do not need to specify a type when declaring a variable, there is one thing that must be specified - the scope of the variable. PHP has four different usage scopes: local, global, static, parameter, which will be introduced separately below.
Local variable (local variable)
Declared in function, it can only be used in the declared function (local scope). Local variables with the same name can be declared in different functions.
At the end of declaring the variable function, the local variable will have no effect
No need to use any keywords when declaring
$a = 5; // Global variable
functionmyTest()
{echo $a; // local variable}
myTest();
The above example will not input anything because $a has no value specified in the function.
Global variable (global variable)
Declared outside the function, except that the script in the function cannot access it, the script in the entire web page can access the variable (global scope). To use global variables in function, you need to use the keyword global, see the following example:
Global variables will not work when the web page is closed
$a = 5; $b = 10; functionmyTest() { global $a,$b;//注意这行 $b = $a +$b; } myTest(); echo $b;
The output of the above example is 15.
Once a global variable is declared, PHP will place it in the array of $GLOBALS[index], where index is the name of the variable. I can access this array from the function, or I can directly assign a value to an element in the array to change its value. We rewrite the above example as follows:
$a = 5; $b = 10; functionmyTest() { $GLOBALS['b']= $GLOBALS['a'] + $GLOBALS['b']; } myTest(); echo $b;
staticvariable(static variable)
As mentioned earlier, local variables are deleted at the end of function will not work. But sometimes, when we want a local variable to not be invalidated when the function ends, we can add the keyword -- static before declaring the local variable for the first time.
static$rememberMe;
In this way, each time the function is called, this variable will contain the value obtained the last time the function was called.
It should be noted that static variables are still local variables.
Parameter (parameter, or argument)
Parameter refers to a local variable passed in when calling a function. It will be declared in the parameter list (parameter list) when the function is declared.
functionmyTest($para1,$para2,...)//Declare in parentheses
{//Function source program}
The above is the detailed content of PHP four variable scope comparison. For more information, please follow other related articles on the PHP Chinese website!