Php static variable test, php static variable error parsing for beginners

Source: Internet
Author: User
Php static variable test, php static variable error parsing for beginners

  1. Function myfunc ()

  2. {
  3. Static $ int;

  4. $ Int = 0;

  5. Echo $ int + 1 ."
    ";

  6. }
  7. Echo myfunc ();
  8. Echo myfunc ();
  9. Echo myfunc ();

  10. ?>

The three values in the result are 1, 2, and 3 respectively. However, the actual result cannot be run and the syntax is incorrect. The cause of the subsequent check error is $ int + 1 ."
"This statement should be written as ($ int + 1 )."
", After the change, the program will not report an error, but the value is, 1; in fact, this is not difficult to explain, although $ int is continuously adding 1, however, the result is not assigned to $ int again. $ int will increase progressively.

It is correct to change the code to the following:

  1. Function myfunc ()
  2. {
  3. Static $ int = 0; // php static variable definition
  4. $ Int = $ int + 1;
  5. Echo $ int ."
    ";
  6. }
  7. Echo myfunc ();
  8. Echo myfunc ();
  9. Echo myfunc ();
  10. ?>

Note: the static keyword must be associated with the value assignment (php static variable modifier usage ).

Staitc $ int; $ int = 0;

Error. the running result is also, 1.

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.