Home > Backend Development > PHP Tutorial > php new self() and new static(), phpnewselfstatic_PHP tutorial

php new self() and new static(), phpnewselfstatic_PHP tutorial

WBOY
Release: 2016-07-12 08:56:31
Original
1019 people have browsed it

php new self() and 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>
Copy after login

self refers to the parsing context, not the calling context. In the example, self is resolved to A that defines get_self(), rather than to B that calls self.

The concept of delayed static binding was introduced in php5.3. The most obvious sign of this feature is the new keyword static. static refers to the class being called. In the example B::get_static() will produce a new B instead of instantiating an A

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1112811.htmlTechArticlephp new self() and new static(), phpnewselfstatic class A { public static function get_self() { return new self(); } public static function get_static() { return new static (); }} c...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template