The static keyword in PHP is used to keep a variable value saved or to create a class method/property that can be accessed without creating an object.

A static variable is a variable inside a function that keeps its value after the function execution ends.

Static Variable Inside Function

static $variable_name;
<?php
function add() {
    static $count = 0;
    $count++;
    echo $count;
}

add(); // The Output is : 1
add(); // The Output is : 2
add(); // The Output is : 3

?>
  • The static keyword is used to declare the variable $count as static within the add() function.
  • The variable is initialized with a value of 0 the first time the function is called.
  • $count is retained from the previous call and incremented by 1.

Static Variable Inside Class

A static variable inside a class is a class property that is shared by all objects of the class and can be accessed without creating an object.

<?php
class Student
{
    public static $count = 0;
}
echo Student::$count;
?>

Static variable belongs to class, not object.