概述 正在学习设计模式,之前有一篇文章关于单例模式的文章,重新读了这篇文章,发现对static关键字掌握不是很牢靠,重新温习一下。 static关键字 PHP手册里对static关键字的介绍如下: 复制代码 代码如下: Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).
对该特性的理解,可以参考下手册中的例子 self vs static 用一个demo来直接说明self与static的区别。 self示例: 复制代码 代码如下: <?php class Vehicle { protected static $name = "This is a Vehicle"; public static function what_vehicle() { echo get_called_class()."
"; echo self::$name; } } class Sedan extends Vehicle { protected static $name = "This is a Sedan"; } Sedan::what_vehicle();
程序输出: 复制代码 代码如下: Sedan This is a Vehicle
static示例: 复制代码 代码如下: <?php class Vehicle { protected static $name = "This is a Vehicle"; public static function what_vehicle() { echo get_called_class()."
"; echo static::$name; } } class Sedan extends Vehicle { protected static $name = "This is a Sedan"; } Sedan::what_vehicle();