PHP Static Variable
In the previous chapters we have already seen the different types of PHP variables such as Function parameter,Local variable and Global variable.
PHP Static Variable :
- We know that, when function ends then all the variables declared inside the function are destroyed.
- Static variables are those variables which can hold value when function called again.
- Static variables are declared with preceding keyword static.
Example : PHP Static Variable
<!DOCTYPE html> <html> <body> <?php function modify() { STATIC $count; $count++; print "Count is : $count"; print "<br />"; } modify(); modify(); modify(); modify(); modify(); ?> </body> </html>
Output :
Count is : 1 Count is : 2 Count is : 3 Count is : 4 Count is : 5
Explanation :
We have called function modify() 3 times. Each time previous value is retained and value is modified by the function each time.
STATIC $count; $count++; print "Count is : $count";