Differences between the PHP static keyword and the self keyword instantiation

Source: Internet
Author: User

When instantiated, the static keyword resembles the self keyword, but the static keyword refers to the class being called, while the Self keyword refers to the containing class.

That might not be a good idea, so let's take an example.

First, create a superclass domainobject, which can be shared by its extended classes, followed by the creation of a subclass Document.

code as follows:

 abstract  Class domainobject {public static Span class= "hljs-function" >function create  () {return new self (); }}class document extends domainobject {}document::create ();     

In the sample code, place the common method create () in the parent class, and use the Self keyword as a reference to that class, which is actually the self Keyword to make a hypothesis. in fact, the Self keyword does not have the same effect on the class as it does on the object $this. The Self keyword refers not to the calling context, 6080 new Visual theater it refers to the parsing context. Therefore, the sample code can be run:

PHP Fatal Error:cannot Instantiate abstract class DomainObject in ...

As you can see, the Self keyword is parsed to define the domainobject of Create () instead of the Document class that calls self.

replace the self keyword with the static keyword to get:

 abstract  Class domainobject {public static Span class= "hljs-function" >function create  () {return new static (); }}class document extends domainobject {}document::create ();     

Operation can be done by:

Document Object
{
}

This concludes that the static keyword is similar to the Self keyword, but it refers to the class being called instead of the containing class. In this case, it means that the call Document::create() will generate a new Document object instead of trying to instantiate a DomainObject object.

Differences between the PHP static keyword and the self keyword instantiation

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.