今天在coding的時候,發現了 new static(),覺得實例化的地方不是應該是 new self()嗎?查詢了一下才知道兩者的區別:
1)在有子類集成的時候,兩者的表現不一樣
2)php 5.2及以下的版本不支持 new static()的語法
具體解釋如下: self - 就是這個類,是代碼段裡面的這個類。 static - PHP 5.3加進來的只得是當前這個類,有點像$this的意思,從堆內存中提取出來,訪問的是當前實例化的那個類,那麼 static 代表的就是那個類。 還是看看老外的專業解釋吧: 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() ).
上代碼:
1 class Person { 2 public static function get_self() { 3 return new self(); 4 } 5 6 public static function get_static() { 7 return new static(); 8 } 9 } 10 11 class WangBaoqiang extends Person{} 12 13 echo get_class(WangBaoqiang::get_self()); // Person 14 echo get_class(WangBaoqiang::get_static()); // WangBaoqiang 15 echo get_class(Person::get_static()); // Person
但是如果想讓 子類使用 get_class時,返回的也是 當前子類的名稱('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" */
歡迎大家,批評指正,謝謝