PHP new static 和 new self詳解

來源:互聯網
上載者:User
使用 self:: 或者 __CLASS__ 對當前類的靜態引用,取決於定義當前方法所在的類:使用 static:: 不再被解析為定義當前方法所在的類,而是在實際運行時計算的。也可以稱之為“靜態繫結”,因為它可以用於(但不限於)靜態方法的調用。

最近在一個視頻的評論被問到一個小問題:這裡選擇用static 而不是self有特殊的考慮嗎?或者我們可以這樣轉換一下問題:

PHP 的 new static 和 new self 具體有什麼?

其實這個來看一個例子應該就很清晰了:

class Father { public static function getSelf() {  return new self(); } public static function getStatic() {  return new static(); }}class Son extends Father {}echo get_class(Son::getSelf()); // Fatherecho get_class(Son::getStatic()); // Sonecho get_class(Father::getSelf()); // Fatherecho get_class(Father::getStatic()); // Father

這裡面注意這一行 get_class(Son::getStatic()); 返回的是 Son 這個 class,可以總結如下:

new self

1.self返回的是 new self 中關鍵字 new 所在的類中,比如這裡例子的 :

public static function getSelf() {  return new self(); // new 關鍵字在 Father 這裡 }

始終返回 Father

new static

2.static 則上面的基礎上,更聰明一點點:static 會返回執行 new static() 的類,比如 Son 執行 get_class(Son::getStatic()) 返回的是 Son, Father 執行 get_class(Father::getStatic()) 返回的是 Father

而在沒有繼承的情況下,可以認為 new selfnew static是返回相同的結果。

Tips: 可以用一個好的 IDE 來直接看注釋。比如 PhpStorm:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.