Differences between new static () and new self ()

Source: Internet
Author: User

Long night!

Today, leaders build a local site. It was found that PHP 5.2 could not be built, and the website PHP Code contains more than 5.3 of the content. The leaders forced me to run the changes under 5.2.

Changed and found a place

return new static($val);

This Nima is a magic horse. I have seen it before.

return new self($val);

So I checked the difference between them online.

Self-is the class in the code snippet.

Static-PHP 5.3 only adds the current class, which is a bit like $ this. It is extracted from the heap memory and accessed by the class currently instantiated, static indicates the class.

Let's take a look at the professional explanations of foreigners.

selfRefers to the same class whose methodnewOperation takes place in.

staticIn PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.

In the following example,BInherits both methods fromA.selfIs boundABecause it's defined inA'S implementation of the first method, whereasstaticIs bound to the called class (also seeget_called_class() ).

class A {    public static function get_self() {        return new self();    }    public static function get_static() {        return new static();    }}class B extends A {}echo get_class(B::get_self());  // Aecho get_class(B::get_static()); // Becho get_class(A::get_static()); // A

You can understand this example.

I understand the principle, but the problem has not been solved. How can I solve the return new static ($ Val) problem?

In fact, it is simple to use.Get_class ($ this); as follows

class A {    public function create1() {        $class = get_class($this);
    return new $class(); } public function create2() { return new static(); }}class B extends A {}$b = new B();var_dump(get_class($b->create1()), get_class($b->create2()));/*The result string(1) "B"string(1) "B"*/

 

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.