PHP OOP – Static Methods

In PHP OOP, static methods are methods that belong to a class, rather than an instance of a class. Static methods can be called without creating an object of the class, and they can be used to perform actions that are not specific to any particular instance of the class.

Here’s an example of a class with a static method:

class Math {
    public static function square($num) {
        return $num * $num;
    }
}
echo Math::square(5); // Output: 25

In this example, the Math class has a static method named square(). The square() method takes a single argument ($num) and returns the square of that number. We can call the square() method on the Math class using the :: operator, without creating an object of the class.

echo Math::square(5); // Output: 25

Static methods can also be used to perform operations on a class’s properties. Here’s an example:

class Counter {
    public static $count = 0;
    
    public static function increment() {
        self::$count++;
    }
}
echo Counter::$count; // Output: 0
Counter::increment();
echo Counter::$count; // Output: 1
Counter::increment();
echo Counter::$count; // Output: 2

In this example, the Counter class has a static property named $count, which is initially set to 0. The class also has a static method named increment(), which increments the $count property by 1. We can access the $count property and call the increment() method on the Counter class without creating an object of the class.

echo Counter::$count; // Output: 0
Counter::increment();
echo Counter::$count; // Output: 1
Counter::increment();
echo Counter::$count; // Output: 2

In summary, static methods in PHP OOP are methods that belong to a class, rather than an instance of a class. Static methods can be called without creating an object of the class, and they can be used to perform actions that are not specific to any particular instance of the class. Static methods can also be used to perform operations on a class’s properties.