This article briefly introduces the usage of static variables in php functions. For more information, see. Static is used in the function. after a variable is declared, if this function is called again, it will continue at the initial value. for example, $ sapi will accumulate here.
This article briefly introduces the usage of static variables in php functions. For more information, see.
The instance code is as follows:
- Function sendHeader ($ num, $ rtarr = null)
- {
- Static $ sapi = null;
- If ($ sapi = null)
- {
- $ Sapi = php_sapi_name ();
- }
- Return $ sapi ++;
When reading the PW source code, I found that the setHeader () function uses the static keyword. it is strange that it has never been used before.
Static is used in the function. after a variable is declared, if this function is called again, it will continue at the initial value. for example, $ sapi will accumulate here.
The instance code is as follows:
- ? Echo sendHeader (1 )."
";
- Echo sendHeader (2 )."
";
- Echo sendHeader (3 )."
";
-
- Output:
- ? Apache2handler
- Apache2handles
- Apache2handlet
It is a bit similar to global, but the difference is that scope. static can only act on this function.
A little interesting. you need to study it in depth.
The instance code is as follows:
- Class test
- {
- Public static function (){}
- Public function B (){}
- }
- $ Obj = new test;
Call code
The instance code is as follows:
- Test: ();
- $ Obj-> ();
- $ Obj-> B ();
Another important feature of the variable range is static variable. static variables only exist in local function domains, but their values are not lost when the program runs out of this scope.
Example of static variables
The instance code is as follows:
-
- Function test ()
- {
- Static $ w3sky = 0;
- Echo $ w3sky;
- $ W3sky ++;
- }
- ?>
Now, every time you call the test () function, the $ w3sky value will be output and added.