欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2016年08月19日 14:02:34   作者:wozhuzaisi  
在寫代碼時(shí)發(fā)現(xiàn) new static(),覺得實(shí)例化的地方不是應(yīng)該是 new self()嗎?怎么回事?通過查閱相關(guān)資料才知道具體情況,下面小編整理下方便日后查找

今天在coding的時(shí)候,發(fā)現(xiàn)了 new static(),覺得實(shí)例化的地方不是應(yīng)該是 new self()嗎?查詢了一下才知道兩者的區(qū)別:

  1)在有子類集成的時(shí)候,兩者的表現(xiàn)不一樣

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

簡單通俗的來說, self就是寫在哪個(gè)類里面, 實(shí)際調(diào)用的就是這個(gè)類.所謂的后期靜態(tài)綁定, static代表使用的這個(gè)類, 就是你在父類里寫的static,

然后通過子類直接/間接用到了這個(gè)static, 這個(gè)static指的就是這個(gè)子類, 所以說static和$this很像, 但是static可以用于靜態(tài)方法和屬性等.

具體解釋如下:

self - 就是這個(gè)類,是代碼段里面的這個(gè)類。

static - PHP 5.3加進(jìn)來的只得是當(dāng)前這個(gè)類,有點(diǎn)像$this的意思,從堆內(nèi)存中提取出來,訪問的是當(dāng)前實(shí)例化的那個(gè)類,那么 static 代表的就是那個(gè)類。

還是看看老外的專業(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 Person {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class WangBaoqiang extends Person{}
echo get_class(WangBaoqiang::get_self()); // Person
echo get_class(WangBaoqiang::get_static()); // WangBaoqiang
echo get_class(Person::get_static()); // Person

但是如果想讓 子類使用 get_class時(shí),返回的也是 當(dāng)前子類的名稱('wangbaoqiang'),該怎么做呢。

<?php
class 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()的比較,希望對(duì)大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論