How to use static variables in a PHP function

September 30th, 2012 by Laeeq | 1 comment

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

 

 

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • How much memory do PHP variables use?
  • Manipulating PHP arrays: push, pop, shift, unshift
  • 10 Super Useful PHP Code Snippets
  • Let’s play with php.ini file Configuration
  • 15+ regular expressions for PHP developers
  •  

     

    1. rizwan
      October 1st, 2012 at 12:07 | #1

      Nice ….

    1. No trackbacks yet.