国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

new static() 和 new self() 的區別異同

2019-11-15 01:46:15
字體:
來源:轉載
供稿:網友
new static() 和 new self() 的區別異同

長夜漫漫啊!

今天領導本地搭建一個站。發現用php 5.2 搭建不起來,站PHP代碼里面有很多5.3以上的部分,領導讓苦逼我更改在5.2下能運行。

改著改著發現了一個地方

return new static($val);

這尼瑪是神馬,只見過

return new self($val);

于是上網查了下,他們兩個的區別。

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()).

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());  // Aecho get_class(B::get_static()); // Becho get_class(A::get_static()); // A

這個例子基本上一看就懂了吧。

原理了解了,但是問題還沒有解決,如何解決掉 return new static($val); 這個問題呢?

其實也簡單就是用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()));/*The result string(1) "B"string(1) "B"*/


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 兴海县| 闸北区| 巴林左旗| 建阳市| 景德镇市| 翁源县| 平邑县| 遂川县| 视频| 铁岭县| 安化县| 澄迈县| 临高县| 泗水县| 陆良县| 锦屏县| 德庆县| 海兴县| 年辖:市辖区| 中西区| 嘉禾县| 广元市| 石城县| 玉田县| 拉孜县| 准格尔旗| 于都县| 含山县| 南昌市| 阳西县| 会昌县| 东阳市| 长春市| 昭苏县| 青神县| 南陵县| 遵义市| 黔西| 闵行区| 衢州市| 阿拉善左旗|