Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the reason why php uses static methods

Shulou Source: shulou.com Published: 2022-06-01 12:21:44 10月02日 Update

This article will explain in detail the reasons for the use of static methods in php. I think it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

In PHP, static methods are used because you don't need the class to be instantiated to use them directly. Static methods and static variables always use the same block of memory after creation, while using instances creates multiple memories, and static methods are more efficient than instantiation.

This article operating environment: Windows10 system, PHP7.1 version, Dell G3 computer.

Why does php use static methods

Static methods can be used directly without the need for the class to be instantiated.

Static methods are more efficient than instantiation. The disadvantage of static methods is that they are not destroyed automatically, while instantiated methods can be destroyed.

Static methods and static variables always use the same block of memory after they are created, while the use of instances creates multiple memories.

Static method

(1) static methods cannot access ordinary properties in this class because those properties belong to an object, but can access static properties.

(2) to access static methods or properties from the current class (not a subclass), you can use the self keyword, and self points to the current class, just as $this points to the current object.

(3) static methods cannot be called in the object, and static methods and properties are also called class methods and class properties, so the pseudo variable $this cannot be used in the object.

Advantages of static methods:

(1) it can be used anywhere in the code (assuming the class can be accessed)

(2) each instance of the class can access the static property defined in the class, and the static property can be used to set the value, which can be used by all objects of the class.

(3) static properties or methods can be accessed without an instance object.

This is the end of this article on why php uses static methods. I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Static method instance property object memory variable article reason create multiple place point efficiency way more good practical ordinary code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Huawei OPPO Reno Shulou Tech Info MySQL