PHP new static and new self, staticself

Source: Internet
Author: User

PHP new static and new self, staticself

Recently, I was asked a small question in a video comment: Is there any special consideration for static instead of self? Or we can convert the problem as follows:

What are PHP's new static and new self?

In fact, the following example should be clear:

class Father { public static function getSelf() {  return 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

Pay attention to this line.get_class(Son::getStatic());The returned result isSonThis class can be summarized as follows:

New self

1.selfThe returned result isnew selfMedium keywordnewIn the class, for example:

Public static function getSelf () {return new self (); // The new Keyword is in Father}

Always returnFather.

New static

2.staticOn the basis of the above, it is a little smarter:staticWill return executionnew static()Class, suchSonRunget_class(Son::getStatic())The returned result isSon,FatherRunget_class(Father::getStatic())The returned result isFather

In the absence of inheritance, we can consider thatnew selfAndnew staticReturns the same result.

Tips: You can use a good IDE to directly view comments. For example, PhpStorm:

Happy Hacking

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.