Skip to main content

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

 

 

PHPZAG.COM is a popular PHP tutorial blog that publishes useful tips and tutorials for PHP programmer. If you would like to be kept up to date with our posts, you can subscribe to our RSS Feed

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