PHP class static of static methods and static of static variables are introduced

  • 2020-05-16 06:25:26
  • OfStack

In php, there are two ways to access a class's methods/variables:
1. Create an object $object = new Class() and then use "- > "Call: $object- > attribute/function, provided the variable/method is accessible.
2. Directly call the class method/variable: class::attribute/function, whether static or non-static. But there are conditions:
A. If it is a variable, it needs to be accessible.
B. If it is a method, in addition to being accessible by the method, it also needs to satisfy:
b1) if the method is static, no special conditions;
b2) if it is a non-static method, it is necessary to change the method without using $this, that is, without calling the non-static variable/method. Of course, it is ok to call the static variable/method.

Then let's look at 1 and use $object- > ... And the use of class: :... What's the difference:
1. Use the $object - > ... , you need to execute the constructor to create the object;
2. Use class: :... Calling static methods/variables, no need to execute constructors to create objects;
3. Use class: :... Calling non-static methods/variables does not require the constructor to create the object.

And then the weird thing is, since 2 and 3 are both 1, what's the point of having a static method/variable?
The differences are obvious, as follows:
1. Static variables
The static member retains only one variable value, which is valid for all instances, that is, all instances share the member.
2. Static methods
Static methods can be used directly using class::... To call, rather than static methods, you need to satisfy 1 definite constraint in order to use class::.. , as described earlier

Related articles: