PHP Static Keyword Explained

In PHP, the static keyword is mainly used in two ways.

  1. In a class, the static keyword can be used to define static properties and methods. Static properties and methods can be accessed directly using the class name, without the need to create an instance of the class. Static properties and methods are shared across all instances of the class. For example:
class MyClass {
    public static $staticProperty = 10;

    public static function staticMethod() {
        return "Static method called";
    }
}

echo MyClass::$staticProperty; // 输出 10
echo MyClass::staticMethod(); // 输出 Static method called
  1. In a function, the static keyword can be used to define static variables. Static variables are not destroyed after the function call ends, but instead retain their value for the next call to use. For example:
function increment() {
    static $count = 0;
    $count++;
    return $count;
}

echo increment(); // 输出 1
echo increment(); // 输出 2
echo increment(); // 输出 3

In general, the static keyword is used to define static properties and methods of a class, or to define static variables within a function, allowing them to share data or state among different instances.

bannerAds