PHP static variable

In this chapter you will learn:

  1. What is PHP static variable
  2. Syntax to declare PHP static variable
  3. Note for static variable
  4. Example - static variable

Description

Static variables are still local to a function, they can be accessed only within the function's code. Unlike local variables, which disappear when a function exits, static variables remember their values from one function call to the next.

Syntax

To declare a local variable as static, all you need to do is write the word static before the variable name, and assign an initial value to the variable:

 
static $var = 0;  

Note

The first time the function is called, the variable is set to its initial value.

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.

Example

static variable


<?PHP/*from j a  va 2s. c  o  m*/
        function nextNumber() { 
          static $counter = 0; 
          return ++$counter; 
        } 

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

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What Is Object-Oriented Programming?
  2. What are classes
  3. What are Objects
  4. What are Properties
  5. What are Methods
Home » PHP Tutorial » PHP Function Create
PHP Function
PHP Function Create
PHP Function Parameter
PHP Function Default Parameters
PHP Variable Length Parameter
PHP Function Reference Parameter
PHP Function Return
PHP Return Reference
PHP Variable Scope in Functions
PHP Global Variables
PHP Recursive Functions
PHP Anonymous Function
PHP static variable