Home > Article > Backend Development > Example analysis of variables and constants in PHP
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;">##e6f80b953bad177c6e29aaa5fa5de61f<span style="color:#0000BB;"></span></span> |
uses two dollar signs ($), and it can be used as a variable variable. For example:
##73bdf98888a97702c045f179b68360f3 | # #At this time, both variables are defined: the content of
is "world". Therefore, it can be expressed as:
The above is the detailed content of Example analysis of variables and constants in PHP. For more information, please follow other related articles on the PHP Chinese website!