Press "Enter" to skip to content

What is the Static Scope of a Variable in PHP?

What is the Static Scope of a Variable in PHP?

In PHP, when a function executed, all variables of that function will be deleted if we want to use that local variable after running the function. For that situation, we can use the static keyword at the time of declaring a variable inside a function.

Here is a PHP program example for using static keyword inside a function at the time of local variable declaration:

<html>
    <body>
        <?php
function f1()
{
    static $a=90; //static scope
    $a=$a+1; //increasing value
    echo $a."<br>";
}
f1(); //function calling
f1(); //function calling
f1(); //function calling
        ?>
    </body>
</html>

Output

91
92
93

Here function is calling for three times. Actually when the function is executing for the first time, then the output will be 91 and output will be 92 and 93 when the function is running for the second and third time. A static variable initialized only once. So here the variable will be initialized to 90 when the function is executing for the first time then values will be changed for each calling of function.