PHP中new static() 和 new self() 的區(qū)別介紹
長夜漫漫??!
今天領(lǐng)導本地搭建一個站。發(fā)現(xiàn)用PHP 5.2 搭建不起來,站PHP代碼里面有很多5.3以上的部分,領(lǐng)導讓苦逼我更改在5.2下能運行。
改著改著發(fā)現(xiàn)了一個地方
return new static($val);
這尼瑪是神馬,只見過
return new self($val);
于是上網(wǎng)查了下,他們兩個的區(qū)別。
self – 就是這個類,是代碼段里面的這個類。
static – PHP 5.3加進來的只得是當前這個類,有點像$this的意思,從堆內(nèi)存中提取出來,訪問的是當前實例化的那個類,那么 static 代表的就是那個類。
還是看看老外的專業(yè)解釋吧。
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() ).
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"
*/
- PHP中new static()與new self()的區(qū)別異同分析
- php self,$this,const,static,->的使用
- php類中的$this,static,final,const,self這幾個關(guān)鍵字使用方法
- PHP中static關(guān)鍵字以及與self關(guān)鍵字的區(qū)別
- PHP new static 和 new self詳解
- PHP面向?qū)ο笾衝ew self()與 new static()的區(qū)別淺析
- 淺談PHP中new self()和new static()的區(qū)別
- php類中static與self的使用區(qū)別淺析
相關(guān)文章
PHP開發(fā)工具ZendStudio下Xdebug工具使用說明詳解
我使用的是XAMPP的集成開發(fā)平臺環(huán)境。里面已經(jīng)預(yù)設(shè)了Xdebug的調(diào)試工具,只需要自己改下配置的就可以了2013-11-11php實現(xiàn)遍歷目錄并刪除指定文件中指定內(nèi)容
這篇文章主要介紹了php實現(xiàn)遍歷目錄并刪除指定文件中指定內(nèi)容,本文實現(xiàn)的工具可以用來刪除服務(wù)器上的一句話木馬,需要的朋友可以參考下2015-01-01php常用數(shù)組array函數(shù)實例總結(jié)【賦值,拆分,合并,計算,添加,刪除,查詢,判斷,排序】
這篇文章主要介紹了php常用數(shù)組array函數(shù),結(jié)合實例形式總結(jié)分析了php常用的數(shù)組操作函數(shù),包括數(shù)組的賦值、拆分、合并、計算、添加、刪除、查詢、判斷、排序等,需要的朋友可以參考下2016-12-12JS(jQuery)實現(xiàn)聊天接收到消息語言自動提醒功能詳解【提示“您有新的消息請注意查收”】
這篇文章主要介紹了JS(jQuery)實現(xiàn)聊天接收到消息語言自動提醒功能,結(jié)合實例形式詳細分析了javascript結(jié)合ajax后臺交互實現(xiàn)信息語音提示功能相關(guān)原理與操作技巧,需要的朋友可以參考下2019-04-04