Home >Backend Development >PHP Problem >Why should php use static methods?
In PHP, static methods are used because they can be used directly without the class being instantiated. Static methods and static variables always use the same memory after they are created, while using instances will create multiple memories. , and static methods are more efficient than instantiation.
The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.
Static methods can be used directly without the class being instantiated.
Static methods are more efficient than instantiation. The disadvantage of static methods is that they are not automatically destroyed, while instantiated ones can be destroyed.
Static methods and static variables always use the same memory after creation, while using instances will create multiple memories.
Static method
(1) Static methods cannot access ordinary properties in this class, because those properties belong to an object, but static properties can be accessed;
(2) To access static methods or properties from the current class (not a subclass), you can use the self keyword, self points to the current class, just like $this points to the current object;
(3) Static methods cannot be called in objects. Static methods and properties are also called class methods and class properties, so the pseudo variable $this cannot be used in objects.
Advantages of static methods:
(1) Can be used anywhere in the code (assuming the class can be accessed);
(2 ) Each instance of the class can access the static properties defined in the class. You can use static properties to set values. The value can be used by all objects of the class;
(3) No instance object is required to access Static properties or methods.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Why should php use static methods?. For more information, please follow other related articles on the PHP Chinese website!