Home > Backend Development > PHP Problem > When to use static methods in php

When to use static methods in php

angryTom
Release: 2023-02-27 12:38:01
Original
5241 people have browsed it

When to use static methods in php

When to use static methods in php

Static methods:

Instances generate memory from the beginning of the program running, so it can be called directly and the efficiency will be much higher. However, static memory is limited. If there are too many instances, the program cannot be started directly, and the static memory will be resident.

Non-static methods:

Instance methods start to generate memory and apply for scattered memory when calling, so the efficiency will be much slower, and non-static ones will be released when they are used up. .

Difference:

1. Static methods do not require new, which makes them easier to use.

2. Static is fast and efficient, because the memory is generated by the instance when the program is running, and it is still there after it is used up, but it is not released.

3. Non-static memory is generated when called and released after use.

Static methods are generally used in tool classes
For example:

class Helper{
    public static function fun1(){}
    public static function fun2(){}
}
Copy after login

If it is for any object of the same class, what should this method do? Things are the same and have nothing to do with the object itself. Generally, this method can be defined as a static method.
For example, if I want to obtain the IP address of the client, this method generally has nothing to do with the business logic class, then I can define a tool class, which defines a method: getClientIP()

class Helper{
public static function getClientIP(){
    $ip = $_SERVER["HTTP_X_CLUSTER_CLIENT_IP"];
    if (strlen($ip) <= 0) {
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    if (strlen($ip) <= 0) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    if (strlen($ip) <= 0) {
        $ip = $_SERVER["REMOTE_ADDR"];
    }
    return $ip;
}
}
Copy after login

More For PHP related knowledge, please visit PHP中文网!

The above is the detailed content of When to use static methods in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template