PHP static variable test, beginner PHP static variable error parsing

Source: Internet
Author: User
    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. ?>

Copy Code

Three values in the book are three-in-one. However, the true result is not operational, syntax error, and post-check error is due to $int+1. "
"The wording of this sentence should be written ($int + 1)."
", the program does not error after the change, but the value is 1,1,1; in fact, this is not difficult to explain, $int although the constant increase of 1, but the results have not been assigned to $int, talk about what $int will increase.

The code is correct if you modify it 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. ?>
Copy Code

Note that the static keyword must be combined with the assignment (the use of the PHP static variable modifier), if written in a book

STAITC $int; $int = 0;

Error, the result of the run is also 1,1,1

  • Related Article

    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.