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.
class ClassName {
public static function staticMethod() {
// Code
}
}
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 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 Methods:
Non-Static Methods:
Static methods and properties are accessed using the :: scope resolution operator:
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:
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.