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

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

WBOY
WBOYOriginal
2016-06-13 08:43:521317browse

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn