What is the use of the static keyword in PHP?

The static keyword has two main uses in PHP: inside classes, and inside functions.

1. Static property and method. They belong to the class itself, not to an object. You can use them without creating an object, with the double colon (::).

<?php
class Counter {
    public static $count = 0;

    public static function increase() {
        self::$count++;
    }
}

Counter::increase();
Counter::increase();

echo Counter::$count;
?>

Output:

Tutorials Class - Output Window

2

2. Static variable in a function. A normal variable is deleted when the function ends. A static variable keeps its value between function calls.

<?php
function visit() {
    static $n = 0;
    $n++;
    echo $n . " ";
}

visit();
visit();
visit();
?>

Output:

Tutorials Class - Output Window

1 2 3

Remember that a static method can not use $this, because there is no object.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.