這篇文章主要介紹了PHP中static關(guān)鍵字以及與self關(guān)鍵字的區(qū)別,本文講解了static關(guān)鍵字的定義、遲綁定(Late Static Bindings)、以及與self關(guān)鍵字的區(qū)別等內(nèi)容,需要的朋友可以參考下
概述
正在學(xué)習(xí)設(shè)計(jì)模式,之前有一篇文章關(guān)于單例模式的文章,重新讀了這篇文章,發(fā)現(xiàn)對(duì)static關(guān)鍵字掌握不是很牢靠,重新溫習(xí)一下。
static關(guān)鍵字
PHP手冊(cè)里對(duì)static關(guān)鍵字的介紹如下:
代碼如下:
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 i
大體意思是,將類的屬性和方法聲明為靜態(tài)以后,可以直接訪問靜態(tài)屬性和方法,而不需要實(shí)例化對(duì)象。
PHP中靜態(tài)成員和方法的特性如下:
1.靜態(tài)成員不能通過類的實(shí)例訪問,但是靜態(tài)方法可以。
2.靜態(tài)成員不能通過->運(yùn)算符訪問。
3.在靜態(tài)方法的作用域中,不能出現(xiàn)$this關(guān)鍵字,也就是說不能在靜態(tài)方法中訪問普通的成員變量。
4.靜態(tài)成員和方法,都可以通過類名直接訪問,而無需實(shí)例化對(duì)象。
遲綁定(Late Static Bindings)
下面的內(nèi)容摘自PHP手冊(cè):
代碼如下:
自 PHP 5.3.0 起,PHP 增加了一個(gè)叫做后期靜態(tài)綁定的功能,用于在繼承范圍內(nèi)引用靜態(tài)調(diào)用的類。
準(zhǔn)確說,后期靜態(tài)綁定工作原理是存儲(chǔ)了在上一個(gè)“非轉(zhuǎn)發(fā)調(diào)用”(non-forwarding call)的類名。當(dāng)進(jìn)行靜態(tài)方法調(diào)用時(shí),該類名即為明確指定的那個(gè)(通常在 :: 運(yùn)算符左側(cè)部分);當(dāng)進(jìn)行非靜態(tài)方法調(diào)用時(shí),即為該對(duì)象所屬的類。所謂的“轉(zhuǎn)發(fā)調(diào)用”(forwarding call)指的是通過以下幾種方式進(jìn)行的靜態(tài)調(diào)用:self::,parent::,static:: 以及 forward_static_call()。可用 get_called_class() 函數(shù)來得到被調(diào)用的方法所在的類名,static:: 則指出了其范圍。
對(duì)該特性的理解,可以參考下手冊(cè)中的例子
self vs static
用一個(gè)demo來直接說明self與static的區(qū)別。
self示例:
代碼如下:
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示例:
代碼如下:
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
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注