How to Define and Use Static Methods in PHP

In PHP, static methods allow you to call functions within a class without needing to create an instance of that class first. This article provides a direct guide on how to define static methods using the static keyword, how to execute them using the scope resolution operator (::), and the essential rules to follow when incorporating them into your object-oriented PHP code.

Defining a Static Method

To define a static method, you place the static keyword directly after the visibility modifier (such as public, protected, or private) and before the function keyword inside your class.

class MathHelper {
    public static function add(int $a, int $b): int {
        return $a + $b;
    }
}

Calling a Static Method Externally

To access a static method from outside the class, you do not instantiate the class using the new keyword. Instead, use the class name followed by the scope resolution operator (::) and the method name.

// Calling the static method directly
$result = MathHelper::add(5, 10);

echo $result; // Outputs: 15

Calling a Static Method Internally

If you need to call a static method from another method within the same class, use the self keyword (or static keyword for late static binding) followed by the double colon (::).

class MathHelper {
    public static function add(int $a, int $b): int {
        return $a + $b;
    }

    public static function average(int $a, int $b): float {
        // Calling the static method internally using self
        $sum = self::add($a, $b);
        return $sum / 2;
    }
}

echo MathHelper::average(10, 20); // Outputs: 15

Key Rules and Best Practices