How to use static variables in a PHP function

Sometimes we have to use static variable in a PHP function. Actually static variables maintain its value between function calls. In below example function,  the $count variable initialized as static with “0” value.

  1. <?php
  2. function foo() {
  3. static $count = 0;
  4. $count++;
  5. echo “Count:”.$count.“</br>”;
  6. }
  7. foo();
  8. foo();
  9. foo();
  10. foo();
  11. foo();
  12. ?>

The above function calls would echo following results:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5




A web developer who has a love for creativity and enjoys experimenting with various techniques in both web design and development. If you would like to be kept up to date with our posts, you can follow us on Twitter, or even by subscribing to our RSS Feed.

One thought on “How to use static variables in a PHP function

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera