首頁 >php教程 >php手册 >php new self()和new static(),phpnewselfstatic

php new self()和new static(),phpnewselfstatic

WBOY
WBOY原創
2016-06-13 08:43:521316瀏覽

php new self()和new static(),phpnewselfstatic

<span>class</span><span> A {
  </span><span>public</span> <span>static</span> <span>function</span><span> get_self() {
    </span><span>return</span> <span>new</span><span> self();
  }
 
  </span><span>public</span> <span>static</span> <span>function</span><span> get_static() {
    </span><span>return</span> <span>new</span> <span>static</span><span>();
  }
}
 
</span><span>class</span> B <span>extends</span><span> A {}
 
</span><span>echo</span> <span>get_class</span>(B::get_self()); <span>//</span><span> A</span>
<span>echo</span> <span>get_class</span>(B::get_static()); <span>//</span><span> B</span><span><br /></span><span>echo</span> <span>get_class</span>(A::get_static()); <span>//</span><span> A</span>

self 指的是解析上下文,而不是调用上下文。例子里,self被解析为定义get_self()的A,而不是解析为调用self的B。

php5.3中引入了延迟静态绑定的概念,该特性最明显的标志就是新关键字static。static指的是被调用的类。例子里B::get_static()将生产新的B,而不是实例化一个A

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn