PHP class static (static) method and static (static) variable usage Introduction _php tips

Source: Internet
Author: User
Tags php class
In PHP, there are two ways to access a class's methods/variables:
1. Create Object $object = new Class (), and then use "->" to invoke: $object->attribute/function, provided that the variable/method is accessible.
2. Direct call to class method/variable: class::attribute/function, either static/Non-static. But there are prerequisites:
A. If it is a variable, you need the variable to be accessible.
B. If this is a method, in addition to the method is accessible, you also need to meet:
B1) If it is a static method, there is no special condition;
B2 If it is a non-static method, you need to change the method without using the $this, that is, not to call the Non-static variable/method, of course, there is no problem calling static variables/methods.

Then we'll look at the use of $object-> and use class:: ... What's the difference:
1. Use of $object->., need to execute constructor creation object;
2. Use class::. Call a static method/variable and do not need to perform a constructor creation object;
3. Use class::. Call non-static methods/variables, and do not need to perform constructor creation objects.

Then the strange place came out, and since 2 and 3 are the same, what's the point of static method/variable existence?
The differences are still apparent, as follows:
1. Static variables
A static member retains only one variable value, and that variable value is valid for all instances, that is, all instances share this member.
2. Static method
Static methods can directly use class:: ... To invoke, and the Non-static method needs to meet certain restrictions to use class::. Method call, 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.