Phpstatic static variables

Source: Internet
Author: User
Phpstatic static variables

  1. Function Test ()
  2. {
  3. $ W3sky = 0;
  4. Echo $ w3sky;
  5. $ W3sky ++;
  6. }
  7. ?>

This function sets $ w3sky to 0 and outputs "0" for each call ". Adding $ w3sky ++ to the variable has no effect, because the variable $ w3sky does not exist once the function is exited.

For example, to implement a counting function that does not lose the current count value, you need to define the variable $ w3sky as static and use the php static variable. A simple example of php static variables

  1. Function Test ()
  2. {
  3. Static $ w3sky = 0;
  4. Echo $ w3sky;
  5. $ W3sky ++;
  6. }
  7. ?>

Every time Test () is called, this function outputs the value of $ w3sky and adds one. Static variables also provide a method for processing recursive functions. A recursive function is a method that calls itself. Be careful when writing recursive functions, because infinite recursion may occur without exit. make sure there are methods to stop recursion. The following simple function recursively counts to 10 and uses the static variable $ count to determine when to stop:

2. example of static variables and recursive functions:

  1. Function Test ()
  2. {
  3. Static $ count = 0;
  4. $ Count ++;
  5. Echo $ count;
  6. If ($ count <10 ){
  7. Test ();
  8. }
  9. $ Count --;
  10. }
  11. ?>

Note: static variables can be declared according to the preceding example. If a value is assigned to the expression result in the declaration, the parsing error occurs. 3. example of declaring static variables:

  1. Function foo (){
  2. Static $ int = 0; // correct
  3. Static $ int = 1 + 2; // wrong (as it is an expression)
  4. Static $ int = sqrt (121); // wrong (as it is an expression too)
  5. $ Int ++;
  6. Echo $ int;
  7. }
  8. ?>

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.