When using static variables, the most important thing to note is to clear them. If we do not clear them, we may encounter some problems, today, let's take a look at the details and examples of PHP static variables, as shown below. When using static variables, the most important thing to note is to clear them. If we do not clear them, we may encounter some problems, today, let's take a look at the details and examples of PHP static variables, as shown below.
Script ec (2); script
As long as the keyword static is added before the variable, the variable becomes a static variable.
Function test ()
{
Static $ nm =;
$ Nm = $ nm *;
Print $ nm ."
";
}
// The first execution, $ nm =
Test ();
// The first execution, $ nm =
Test ();
// The first execution, $ nm =
Test ();
?>
Program running result:
1
2
2
4
3
8
After the test () function is executed, the values of the variable $ nm are saved.
Static attributes are often used in class, such as static members and static methods.
The younger brother of the previous company is going to interview PHP. He has encountered a PHP basic interview question. The general content is as follows:
Function test (){
Static $ a = 0;
$ A ++;
Echo "before unset". $ ."
";
Unset ($ );
$ A = 23;
Echo "after unset". $ ."
";
}
Test ();
Test ();
Test ();
When I saw this question, I noticed the stats mark $. This question won't be the result of the first response. (The result is as follows)
PHP running result
This $ a value has not changed because of the unset () function, but has been accumulating !! I know that the static state variable corresponding to unset () is invalid. I checked the Manual now.
Unset ()Destroys the specified variable.
Unset ()The behavior in a function varies depending on the type of the variable to be destroyed.
IfUnset ()A global variable is destroyed, while the variables in the call environment will keep callingUnset ()The same value.
IfUnset ()A static variable is destroyed within the function. However, when this function is called again, the static variable is restored to the value before the previous destruction.
In fact, this understanding is as follows:
PHP variable Diagram
PHP memory addresses and variables are directly associated in this way. Generally, variables are associated to point to the corresponding address, rather than the real value. Therefore, the unset () process is actually disconnected, rather than the value of the memory address.
Static variables exist only in the local function domain. However, when the execution of a program leaves this scope, the value of static variables is not lost.