A brief analysis of the difference between PHP static method and static variable

Source: Internet
Author: User
This article introduces the difference between static and static variables in PHP class, if the method is non-static, it is not necessary to use $this, that is, no non-static variable/method is called, of course, there is no problem in calling static variable/method.

About the use of static and static methods in PHP .

In PHP, there are two methods of accessing a class's Methods/variables: 1, creating the object $object = new Class (), and then using the call: $object->attribute/function, provided the variable/method is accessible. 2, directly call the class method/variable: class::attribute/function, either static/non-static can be. But there are prerequisites: a. If it is a variable, it needs to be accessible. B. If it is a method, in addition to the method can be accessed, but also need to satisfy: B1) If it is a static method, there is no special condition; b2) If the method is non-static, it is not necessary to use $this, that is, the non-static variable/method is not called, of course, there is no problem calling the static

Then look at the use of $object-> and use class:: ... What is the difference:

1, use $object->., need to execute constructor to create object; 2, use class:: ... Call static method/variable, do not need to execute constructor to create object; 3, use class:: ... Call a non-static method/variable and do not need to execute the constructor to create the object.

Since 2 and 3 are all the same, what is the point of static methods/variables? Difference: 1 static variable static members retain only one variable value, and this variable value is valid for all instances, that is, all instances share this member. 2 static method static method can directly use the class: ... Instead of static methods that require certain restrictions to use class::. Method calls, as described earlier.

  • 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.