亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

PHP中static關(guān)鍵字以及與self關(guān)鍵字的區(qū)別

 更新時間:2015年07月01日 15:53:00   投稿:junjie  
這篇文章主要介紹了PHP中static關(guān)鍵字以及與self關(guān)鍵字的區(qū)別,本文講解了static關(guān)鍵字的定義、遲綁定(Late Static Bindings)、以及與self關(guān)鍵字的區(qū)別等內(nèi)容,需要的朋友可以參考下

概述

正在學(xué)習(xí)設(shè)計模式,之前有一篇文章關(guān)于單例模式的文章,重新讀了這篇文章,發(fā)現(xiàn)對static關(guān)鍵字掌握不是很牢靠,重新溫習(xí)一下。

static關(guān)鍵字

PHP手冊里對static關(guān)鍵字的介紹如下:

復(fù)制代碼 代碼如下:

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).

大體意思是,將類的屬性和方法聲明為靜態(tài)以后,可以直接訪問靜態(tài)屬性和方法,而不需要實例化對象。

PHP中靜態(tài)成員和方法的特性如下:

1.靜態(tài)成員不能通過類的實例訪問,但是靜態(tài)方法可以。
2.靜態(tài)成員不能通過->運算符訪問。
3.在靜態(tài)方法的作用域中,不能出現(xiàn)$this關(guān)鍵字,也就是說不能在靜態(tài)方法中訪問普通的成員變量。
4.靜態(tài)成員和方法,都可以通過類名直接訪問,而無需實例化對象。

遲綁定(Late Static Bindings)

下面的內(nèi)容摘自PHP手冊:

復(fù)制代碼 代碼如下:

自 PHP 5.3.0 起,PHP 增加了一個叫做后期靜態(tài)綁定的功能,用于在繼承范圍內(nèi)引用靜態(tài)調(diào)用的類。
準確說,后期靜態(tài)綁定工作原理是存儲了在上一個“非轉(zhuǎn)發(fā)調(diào)用”(non-forwarding call)的類名。當進行靜態(tài)方法調(diào)用時,該類名即為明確指定的那個(通常在 :: 運算符左側(cè)部分);當進行非靜態(tài)方法調(diào)用時,即為該對象所屬的類。所謂的“轉(zhuǎn)發(fā)調(diào)用”(forwarding call)指的是通過以下幾種方式進行的靜態(tài)調(diào)用:self::,parent::,static:: 以及 forward_static_call()??捎?get_called_class() 函數(shù)來得到被調(diào)用的方法所在的類名,static:: 則指出了其范圍。

對該特性的理解,可以參考下手冊中的例子

self vs static

用一個demo來直接說明self與static的區(qū)別。
self示例:

復(fù)制代碼 代碼如下:

<?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();

程序輸出:
復(fù)制代碼 代碼如下:

Sedan
This is a Vehicle

static示例:
復(fù)制代碼 代碼如下:

<?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();

程序輸出:

復(fù)制代碼 代碼如下:

Sedan
This is a Sedan

總結(jié)

看看上一篇文章,已經(jīng)一個多月沒更新過博客了,忙是一部分,主要的還是自己懈怠了,以后還得堅持。這篇文章寫的也有點沒感覺。

相關(guān)文章

最新評論