雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網!

PHP編程

當前位置:主頁 > 網絡編程 > PHP編程 >

PHP的new static和new self的區(qū)別與使用

來源:本站原創(chuàng)|時間:2020-01-11|欄目:PHP編程|點擊:

下面我們舉個栗子:

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()); // Father
echo get_class(Son::getStatic()); // Son
echo get_class(Father::getSelf()); // Father
echo get_class(Father::getStatic()); // Father

new self

這里面注意這一行 get_class(Son::getStatic()); 返回的是 Son 這個 class, 可以總結如下:
self 返回的是 new self 中關鍵字 new 所在的類中,比如這里例子的 :

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

始終返回 Father。

new static

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

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持我們。

上一篇:Laravel框架Eloquent ORM刪除數(shù)據操作示例

欄    目:PHP編程

下一篇:Laravel框架基礎語法與知識點整理【模板變量、輸出、include引入子視圖等】

本文標題:PHP的new static和new self的區(qū)別與使用

本文地址:http://www.jygsgssxh.com/a1/PHPbiancheng/11075.html

網頁制作CMS教程網絡編程軟件編程腳本語言數(shù)據庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網 版權所有