首页 >后端开发 >php教程 >php new self()和new static(),phpnewselfstatic_PHP教程

php new self()和new static(),phpnewselfstatic_PHP教程

WBOY
WBOY原创
2016-07-12 08:56:31970浏览

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1112811.htmlTechArticlephp new self()和new static(),phpnewselfstatic class A { public static function get_self() { return new self(); } public static function get_static() { return new static (); }} c...
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn