PHP延遲靜態繫結:static關鍵字

來源:互聯網
上載者:User

標籤:his   bsp   sheet   方法   static關鍵字   extend   使用   階層   結構   

  PHP5.3中引入了延遲靜態繫結的概念。該特性最明顯的標誌就是新關鍵字static。static類似於self,但它指的是被調用的類而不是包含類。在本例中,它的意思是調用Document::create()將產生一個新的Document對象,而不是試圖執行個體化一個DomainObject對象。

  因此,現在在靜態上下文中使用繼承關係。

  

abstract class DomainObject{    public static function create(){        return new static();    }}class User extends DomainObject{    }class Document extends DomainObject{    }print_r(Document::create());

------------------------------------

Document Object

(

)

-------------------------------------

  static 關鍵字不僅僅可以用於執行個體化。和self和parent一樣,static還可以作為靜態方法調用的標識符,甚至是從非靜態上下文中調用。假設我想為DomainObject引入組的概念。預設情況下,所有類都屬於default類別,但我想能為繼承階層的某些分支重寫類別。

  

abstract class DomainObject{    private $group;        public function __construct(){        $this->group = static::getGroup();    }        public static function create(){        return new static();    }        static function getGroup(){        return "default";    }}class User extends DomainObject{    }class Document extends DomainObject{    static function getGroup(){        return "document";    }}class SpreadSheet extends Document{    }print_r(User::create());print_r(SpreadSheet::create());

  在DomainObject類中定義了建構函式。該建構函式使用static關鍵字調用靜態方法getGroup()。DomainObject提供了預設實現,但Document將其覆蓋了。我還建立了一個新類SpreadSheet,該類擴充了Document類。下面是輸出:

---------------------------------------

User Object

(

  [group:DomainObject:private] => default

)

SpreadSheet Object

(

  [group:DomainObject:private] => document

)

---------------------------------------

  User類不需要實現太多功能。DomainObject建構函式調用了getGroup()類,並在本地進行尋找。對於SpreadSheet,雖然搜尋從被調用的類SpreadSheet本身開始,但它沒有提供任何實現,因此調用類Document中的getGroup()方法。PHP5.3以前未引入延遲靜態繫結,self關鍵字只尋找DomainObject類中的getGroup(),因此遇到self關鍵字的時候我無計可施。

 

PHP延遲靜態繫結:static關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.