2017-12-05 16:47:59 1431瀏覽
今天扣丁學(xué)堂給大家相許介紹一下關(guān)于PHP中new static()與new self()的區(qū)別異同,相信對(duì)于大家學(xué)習(xí)PHP全棧開(kāi)發(fā)工程師設(shè)計(jì)能夠帶來(lái)一定的幫助。問(wèn)題的起因是本地搭建一個(gè)站。發(fā)現(xiàn)用PHP 5.2 搭建不起來(lái),站PHP代碼里面有很多5.3以上的部分,要求更改在5.2下能運(yùn)行。
改著改著發(fā)現(xiàn)了一個(gè)地方:
return new static($val);
這是神馬,只見(jiàn)過(guò):
return new self($val);
于是網(wǎng)上查了一下,他們兩個(gè)的區(qū)別。
self - 就是這個(gè)類(lèi),是代碼段里面的這個(gè)類(lèi)。
static - PHP 5.3加進(jìn)來(lái)的只得是當(dāng)前這個(gè)類(lèi),有點(diǎn)像$this的意思,從堆內(nèi)存中提取出來(lái),訪問(wèn)的是當(dāng)前實(shí)例化的那個(gè)類(lèi),那么 static 代表的就是那個(gè)類(lèi)。
還是看看老外的專(zhuān)業(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
這個(gè)例子基本上一看就懂了吧。
原理了解了,但是問(wèn)題還沒(méi)有解決,如何解決掉 return new static($val); 這個(gè)問(wèn)題呢?
其實(shí)也簡(jiǎn)單就是用 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()));
結(jié)果:
string(1) "B"
string(1) "B"
以上就是關(guān)于PHP培訓(xùn)中new static()與new self()區(qū)別異同分析的詳細(xì)介紹,這個(gè)static在php單例模式時(shí)常用, 注意php的版本問(wèn)題,最后想要學(xué)習(xí)PHP開(kāi)發(fā)技術(shù)的小伙伴不要猶豫了,扣丁學(xué)堂是你學(xué)習(xí)PHP技術(shù)的最佳選擇,想要PHP視頻教程的小伙伴現(xiàn)在就聯(lián)系我們的咨詢老師領(lǐng)取吧,機(jī)會(huì)總是留給有準(zhǔn)備的人的! 扣丁學(xué)堂PHP技術(shù)交流群:374332265。
【關(guān)注微信公眾號(hào)免費(fèi)領(lǐng)取丁豆獲取更多的學(xué)習(xí)資料】
查看更多關(guān)于“php培訓(xùn)資訊”的相關(guān)文章>>