PHP : OOP - Static Methods

In PHP, static methods are methods that are called on a class itself, rather than on an instance of the class (an object). These methods are declared using the static keyword, and they can be called directly without creating an instance of the class. Static methods can access static properties and other static methods within the same class.

Static Method Syntax:

class ClassName {
    public static function staticMethod() {
        // Code
    }
}

 

Calling Static Methods:

Static methods are called using the ClassName::methodName() syntax, where ClassName is the name of the class containing the static method.


class Math {
    public static function square($num) {
        return $num * $num;
    }
}

// Calling a static method
$result = Math::square(5);
echo "Square of 5 is: " . $result; // Output: Square of 5 is: 25

Static Properties:

Static methods can also access static properties (class variables). Static properties are declared using the static keyword inside the class. They are shared among all instances of the class.

Example with Static Properties and Methods:


class Counter {
    public static $count = 0;

    public static function increment() {
        self::$count++;
    }

    public static function getCount() {
        return self::$count;
    }
}

Counter::increment();
Counter::increment();
echo "Count: " . Counter::getCount(); // Output: Count: 2

 

Static vs. Non-Static Methods:

Static Methods:

  •   Can be called without creating an instance of the class.
  •   Cannot access non-static (instance) properties or methods directly.
  •   Useful for utility methods, like helper functions.

Non-Static Methods:

  •   Require an instance of the class to be created before they can be called.
  •   Can access non-static properties and methods of the class.
  •   Used for methods that are specific to an instance of the class.

 Accessing Static Methods and Properties:

Static methods and properties are accessed using the :: scope resolution operator:

  • To access a static method: ClassName::methodName()
  • To access a static property: ClassName::$propertyName

Static Methods Example:

Here's a more complete example demonstrating the use of static methods and properties:


class Logger {
    public static $logFile = "log.txt";

    public static function log($message) {
        $timestamp = date("Y-m-d H:i:s");
        $logEntry = "$timestamp - $message\n";
        file_put_contents(self::$logFile, $logEntry, FILE_APPEND);
    }

    public static function readLogs() {
        return file_get_contents(self::$logFile);
    }
}

// Logging messages
Logger::log("Error: Something went wrong!");
Logger::log("Warning: This is a warning message.");

// Reading and displaying logs
echo Logger::readLogs();

 

In this example:

  • The Logger class has a static property $logFile and two static methods: log() and readLogs().
  • The log() method logs a message with a timestamp to a log file.
  • The readLogs() method reads and returns the contents of the log file.
  • These static methods and properties can be accessed and used without creating an instance of the Logger class.

When to Use Static Methods:

  • Use static methods when the functionality does not depend on the state of a specific instance.
  • Use static methods for utility functions, operations on class-level data, or when you want to avoid creating unnecessary instances.

Static Methods and Inheritance:

  • Static methods can be inherited by child classes.
  • When a child class overrides a parent class's static method, it does not hide the parent's method; both methods will coexist.
  • When a child class calls a parent class's static method, it uses the parent's method unless it overrides it.

Conclusion:

Static methods in PHP allow you to define methods that can be called directly on a class without creating an instance. They are useful for utility functions, operations on class-level data, or when you want to avoid the overhead of creating instances. Static methods can access static properties and other static methods within the same class. Understanding static methods is important for designing classes with shared behavior and for creating reusable, efficient code.