new static()與new self()的差異用法介紹

伊谢尔伦
發布: 2023-03-11 08:04:01
原創
1493 人瀏覽過

這篇文章主要介紹了PHP中new static()與new self()的區別異同分析,是很實用的技巧,相信對於大家學習PHP程式設計能夠帶來一定的幫助。

問題的起因是本地搭建一個站。發現用PHP 5.2 搭建不起來,站PHP程式碼裡面有很多5.3以上的部分,要求更改在5.2下能運作。

改著改著發現了一個地方

return new static($val);
登入後複製

這尼瑪是神馬,只見過

return new self($val);
登入後複製

於是上網查了下,他們兩個的區別。

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 implement of the firstas static is bound to the called class (also see  get_called_class() ).

class A {
  public static function get_self() {
    return new self();
  }

  public static function get_static() {
    return new static();
  }
}

class B extends A {}

echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_static()); // A
登入後複製

這個例子基本上一看就懂了吧。

原理了解了,但是問題還沒解決,要如何解決掉 return new static($val); 這個問題呢?

其實也簡單就是用 get_class($this); 程式碼如下:

class A {
  public function create1() {
    $class = get_class($this);
    return new $class();
  }
  public function create2() {
    return new static();
  }
}

class B extends A {

}

$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));

/*
The result 
string(1) "B"
string(1) "B"
*/
登入後複製

有興趣的朋友可以動手測試範例程式碼,相信會有新的收穫!

以上是new static()與new self()的差異用法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!