静态属性和变量
使用 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);