Use static variables in php functions

Source: Internet
Author: User
The code is as follows: Copy code

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 code is as follows: Copy code

? Echo sendHeader (1). "<br> ";
Echo sendHeader (2). "<br> ";
Echo sendHeader (3). "<br> ";


Output:

? Apache2handler
Apache2handles
Apache2handlet

It is a bit similar to global, but the difference is the scope. Static can only act on this function.

A little interesting. In-depth research is required.

 

The code is as follows: Copy code
Class test
{
Public static function (){}
Public function B (){}
}
$ Obj = new test;

Call code

The code is as follows: Copy code

Test: ();
$ Obj-> ();
$ Obj-> B ();

Another important feature of 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 code is as follows: Copy code
<? Php
Function test ()
   {
Static $ w3sky = 0;
Echo $ w3sky;
$ W3sky ++;
   }
?>

Now, every time you call the test () function, the value of $ w3sky is output and added with one.


For more details, see: http://www.111cn.net/phper/php/php-static.htm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.