Home >Backend Development >PHP Tutorial >php new self和new static
<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>echo</span><span>get_class</span>(A::get_static()); <span>//</span><span> A</span>
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 PHP 5.3. The most obvious symbol 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
The above introduces php new self and new static, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.