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

 

 

Leave a Reply

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

Shares

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!