PHP - Static Variables
Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −
- Local variables
- Function parameters
- Global variables
- Static variables.
Static Variables
The final type of variable scoping that I discuss is known as static. In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.
Live Demo<?php function keep_track() { STATIC $count = 0; $count++; print $count; print "<br />"; } keep_track(); keep_track(); keep_track(); ?>
This will produce the following result −
1 2 3