概述
正在學習設計模式,之前有一篇文章關於單例模式的文章,重新讀了這篇文章,發現對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).
大體意思是,將類的屬性和方法聲明為靜態以後,可以直接存取靜態屬性和方法,而不需要執行個體化對象。
PHP中靜態成員和方法的特性如下:
1.靜態成員不能通過類的執行個體訪問,但是靜態方法可以。
2.靜態成員不能通過->運算子訪問。
3.在靜態方法的範圍中,不能出現$this關鍵字,也就是說不能在靜態方法中訪問普通的成員變數。
4.靜態成員和方法,都可以通過類名直接存取,而無需執行個體化對象。
遲綁定(Late Static Bindings)
下面的內容摘自PHP手冊:
複製代碼 代碼如下:
自 PHP 5.3.0 起,PHP 增加了一個叫做後期靜態繫結的功能,用於在繼承範圍內引用靜態調用的類。
準確說,後期靜態繫結工作原理是儲存了在上一個“非轉寄調用”(non-forwarding call)的類名。當進行靜態方法調用時,該類名即為明確指定的那個(通常在 :: 運算子左側部分);當進行非靜態方法調用時,即為該對象所屬的類。所謂的“轉寄調用”(forwarding call)指的是通過以下幾種方式進行的靜態調用:self::,parent::,static:: 以及 forward_static_call()。可用 get_called_class() 函數來得到被調用的方法所在的類名,static:: 則指出了其範圍。
對該特性的理解,可以參考下手冊中的例子
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()."\n";
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()."\n";
echo static::$name;
}
}
class Sedan extends Vehicle {
protected static $name = 'This is a Sedan';
}
Sedan::what_vehicle();
程式輸出:
複製代碼 代碼如下:
Sedan
This is a Sedan
總結
看看上一篇文章,已經一個多月沒更新過部落格了,忙是一部分,主要的還是自己懈怠了,以後還得堅持。這篇文章寫的也有點沒感覺。