《PHP編程:PHP中new static() 和 new self() 的區別介紹》要點:
本文介紹了PHP編程:PHP中new static() 和 new self() 的區別介紹,希望對您有用。如果有疑問,可以聯系我們。
長夜漫漫啊!PHP編程
今天領導本地搭建一個站.發現用PHP 5.2 搭建不起來,站PHP代碼里面有很多5.3以上的部分,領導讓苦逼我更改在5.2下能運行.PHP編程
改著改著發現了一個地方
PHP編程
self C 就是這個類,是代碼段里面的這個類.PHP編程
static C PHP 5.3加進來的只得是當前這個類,有點像$this的意思,從堆內存中提取出來,訪問的是當前實例化的那個類,那么 static 代表的就是那個類.PHP編程
還是看看老外的專業解釋吧.PHP編程
self refers to the same class whose method the new operation takes place in.PHP編程
static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.PHP編程
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編程
??? public static function get_static() {
??????? return new static();
??? }
}PHP編程
class B extends A {}PHP編程
echo get_class(B::get_self());? // A
echo get_class(B::get_static()); // B
echo get_class(A::get_static()); // A
PHP編程
原理了解了,但是問題還沒有解決,如何解決掉 return new static($val); 這個問題呢?PHP編程
其實也簡單就是用 get_class($this); 如下
PHP編程
class B extends A {PHP編程
}PHP編程
$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));PHP編程
/*
The result
string(1) "B"
string(1) "B"
*/
PHP編程
歡迎參與《PHP編程:PHP中new static() 和 new self() 的區別介紹》討論,分享您的想法,維易PHP學院為您提供專業教程。