靜態屬性和變數

使用 public 可見性定義的靜態類屬性在功能上與全域性變數相同。可以從定義類的任何位置訪問它們。

class SomeClass {
    public static int $counter = 0;
}

// The static $counter variable can be read/written from anywhere
// and doesn't require an instantiation of the class
SomeClass::$counter += 1;

函式還可以在自己的範圍內定義靜態變數。與函式作用域中定義的常規變數不同,這些靜態變數通過多個函式呼叫持久存在。這可以是實現 Singleton 設計模式的一種非常簡單和簡單的方法:

class Singleton {
    public static function getInstance() {
        // Static variable $instance is not deleted when the function ends
        static $instance;

        // Second call to this function will not get into the if-statement,
        // Because an instance of Singleton is now stored in the $instance
        // variable and is persisted through multiple calls
        if (!$instance) {
            // First call to this function will reach this line,
            // because the $instance has only been declared, not initialized
            $instance = new Singleton();
        }

        return $instance;

    }
}

$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

// Comparing objects with the '===' operator checks whether they are
// the same instance. Will print 'true', because the static $instance
// variable in the getInstance() method is persisted through multiple calls
var_dump($instance1 === $instance2);