PHP static variable
In this chapter you will learn:
- What is PHP static variable
- Syntax to declare PHP static variable
- Note for static variable
- 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:
- What Is Object-Oriented Programming?
- What are classes
- What are Objects
- What are Properties
- What are Methods