PHP - Function Static Variables

Introduction

Static variables are local to a function.

Static variables remember their values from one function call to the next.

To declare a local variable as static, write the word vstatic before the variable name, and assign an initial value to the variable:

static $var = 0;

The first time the function is called, the variable is set to its initial value, zero in this example.

However, if the variable's value is changed within the function, the new value is remembered the next time the function is called.

The value is remembered only as long as the script runs, so the next time you run the script the variable is reinitialized.

Demo

<?php
        function nextNumber() {
          static $counter = 0;
          return ++$counter;//from  ww w.j a  v  a 2s.c o  m
        }

        echo"I've counted to:". nextNumber()."\n";
        echo"I've counted to:". nextNumber()."\n";
        echo"I've counted to:". nextNumber()."\n";
?>

Result