PHP中new static()與new self()的比較

來源:互聯網
上載者:User

標籤:

  今天在coding的時候,發現了 new static(),覺得執行個體化的地方不是應該是 new self()嗎?查詢了一下才知道兩者的區別:

  1)在有子類整合的時候,兩者的表現不一樣

  2)php 5.2及以下的版本不支援 new static()的文法

 

具體解釋如下:self - 就是這個類,是程式碼片段裡面的這個類。static - PHP 5.3加進來的只得是當前這個類,有點像$this的意思,從堆記憶體中提取出來,訪問的是當前執行個體化的那個類,那麼 static 代表的就是那個類。還是看看老外的專業解釋吧:self refers to the same class whose method the new operation takes place in.static in PHP 5.3‘s late static bindings refers to whatever class in the hierarchy which you call the method on.In the following example, B inherits both methods from A. self is bound to A because it‘s defined in A‘s implementation of the first method, whereas static is bound to the called class (also see  get_called_class() ).

 

上代碼:

 

 1 class Person { 2   public static function get_self() { 3     return new self(); 4   } 5   6   public static function get_static() { 7     return new static(); 8   } 9 }10  11 class WangBaoqiang extends Person{}12  13 echo get_class(WangBaoqiang::get_self()); // Person14 echo get_class(WangBaoqiang::get_static()); // WangBaoqiang15 echo get_class(Person::get_static()); // Person

 

但是如果想讓 子類使用 get_class時,返回的也是 當前子類的名稱(‘wangbaoqiang‘),該怎麼做呢。

<?phpclass Person {  public function create1() {    $class = get_class($this);    return new $class();  }  public function create2() {    return new static();  }} class WangBaoqiang extends Person { } $wangBaoQiang = new WangBaoqiang();var_dump(get_class($wangBaoQiang->create1()), get_class($wangBaoQiang->create2())); /*The result string(1) "WangBaoqiang"string(1) "WangBaoqiang"*/

 

 

歡迎大家,批評指正,謝謝

 

PHP中new static()與new self()的比較

聯繫我們

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