PHP: Static variable

This entry is part 8 of 54 in the series PHP Tutorial

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

Consider the following example:

<?php
function final_no()
{
    static $num = 0;
    echo $num;
    $num++;
    echo "<br>";
}

final_no();
final_no();
final_no();

?>
Try The Code

The output from the above code is 0, 1, 2.

The $num was declared once as a static variable and will be initialized on the first call to final_no().  Everytime final_no() is called, $num will not be re-initialized to 0.

Series Navigation<< PHP: Variable scope
PHP: Constants >>