About PHP new static and new self

Source: Internet
Author: User
Use self:: or __class__ a static reference to the current class, depending on the class in which the current method is defined: Using static:: Is no longer resolved to define the class in which the current method resides, but is evaluated at the actual run time. It can also be called a "static binding" because it can be used (but not limited to) the invocation of a static method.

A recent comment in a video was asked a small question: Is there a special consideration for static instead of self? Or we can change the question like this:

What is the new static and new self of PHP specific?

In fact, this one example should be very clear:

Class Father {public static function getself () {  return to new self (),} public static function Getstatic () {  return New Static (); }}class Son extends Father {}echo get_class (son::getself ()); Fatherecho Get_class (Son::getstatic ()); Sonecho Get_class (Father::getself ()); Fatherecho Get_class (Father::getstatic ()); Father

Note that this line get_class(Son::getStatic()); returns the Son class, which can be summed up as follows:

New self

1. self returns the class in which the new self keyword is new located, as in the example here:

public static function Getself () {  return new self ();//New keyword is here in Father}

Always returns Father .

New static

2. static on the above basis, a little bit smarter: The static class that will return execution new static() , such as execution returns, is the Son execution that get_class(Son::getStatic()) Son Father get_class(Father::getStatic()) returns theFather

In the case of no inheritance, the same result can be considered new self and new static returned.

Tips: You can use a good IDE to see the annotations directly. such as Phpstorm:

The above is the whole content of this article, I hope that everyone's study has helped.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.