Static variable in PHP language

A static variable is similar to a local variable. The only difference is that the static variable retains its value even after the function terminates. When a function terminates, the local variable of that function lose their values. To retain the value of the variable through the execution of the program, use the static keyword with the variable name. Static variable are only accessible from within the function they are declared and their value remains intact between function calls. Static variable can be initialized during declaration and the static declaration are resolved during compile time. The web developers static variable is commonly used in the recursive functions. A recursive function calls itself recursively with in a function.

 

The syntax to declare a static variable is as follows:

 

Syntax:

static $var_name = value ;

Where,

var_name – defines the variable name

value – specifies the value of the variable

 

<?php

$var_one;

Function sum()

{

static $var_one = 10;

$var2 = $var_one + 12;

echo “The value of variable is : $var_one <br /> ”;

echo “The addition value of 10 + 12 =  ”;

echo “$var2<br> ”;

}

sum();

?>

 

OUTPUT:

 

The value of the variable is: 9

The addition value of 10 + 12 = 22