《PHP編程:PHP中new static()與new self()的比較》要點(diǎn):
本文介紹了PHP編程:PHP中new static()與new self()的比較,希望對(duì)您有用。如果有疑問(wèn),可以聯(lián)系我們。
今天在coding的時(shí)候,發(fā)現(xiàn)了 new static(),覺(jué)得實(shí)例化的地方不是應(yīng)該是 new self()嗎?查詢了一下才知道兩者的區(qū)別:
PHP實(shí)例
1)在有子類集成的時(shí)候,兩者的表現(xiàn)不一樣
PHP實(shí)例
2)php 5.2及以下的版本不支持 new static()的語(yǔ)法
PHP實(shí)例
簡(jiǎn)單通俗的來(lái)說(shuō), self就是寫(xiě)在哪個(gè)類里面, 實(shí)際調(diào)用的就是這個(gè)類.所謂的后期靜態(tài)綁定, static代表使用的這個(gè)類, 就是你在父類里寫(xiě)的static, PHP實(shí)例
然后通過(guò)子類直接/間接用到了這個(gè)static, 這個(gè)static指的就是這個(gè)子類, 所以說(shuō)static和$this很像, 但是static可以用于靜態(tài)方法和屬性等.
PHP實(shí)例
具體解釋如下:PHP實(shí)例
self - 就是這個(gè)類,是代碼段里面的這個(gè)類.PHP實(shí)例
static - PHP 5.3加進(jìn)來(lái)的只得是當(dāng)前這個(gè)類,有點(diǎn)像$this的意思,從堆內(nèi)存中提取出來(lái),訪問(wèn)的是當(dāng)前實(shí)例化的那個(gè)類,那么 static 代表的就是那個(gè)類.PHP實(shí)例
還是看看老外的專業(yè)解釋吧:PHP實(shí)例
self refers to the same class whose method the new operation takes place in.PHP實(shí)例
static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.PHP實(shí)例
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() ).
PHP實(shí)例
上代碼:
PHP實(shí)例
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實(shí)例
<?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ì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的.在此也非常感謝大家對(duì)維易PHP網(wǎng)站的支持!PHP實(shí)例
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/4762.html