Introduction
One of the most common ways of working with a class is to create an object and then access its properties and methods:
class Printer {
public function print($message) {
print($message . PHP_EOL);
}
}
$my_printer = new Printer();
$my_printer->print("Hello world.");
However, there are times when it's useful to be able to access a class' properties or methods without having to instantiate that class.
This is possible by making those properties or methods static.
Static methods
Let's modify the printer example:
class Printer {
public static function print($message) {
print($message . PHP_EOL);
}
}
Printer::print("Hello world.");
Because we've made the print() method static, we can call it by using the name of the class, followed by the scope operator ::, followed by the name of the method, and we no longer have to explicitly create a Printer object to call its print() method.
Calling Printer::print() is like saying: "call the print() method specified by the Printer class", instead of saying "create a Printer object and execute that object's print() method."
Why use static methods?
Utility functions and singletons are the most common reasons to use static methods.
Utility functions
You can use static methods to create utility functions that are not tied to a specific instance of a class, and perform tasks that are not related to any specific object's state (the values of its properties).
In the Printer example, we don't need to configure the Printer object, provide values, or do other things before it can do its job. We simply need to print() something and move on.
In such a case it would be wasteful to create a Printer object that uses processing time and memory, when we could directly call Printer::print() and be done.
Singletons
Some situations require that only 1 instance of a class can ever exist at any given time. The singleton code pattern relies on static methods to make this work.
The details of how to create and use singletons is outside the scope of this unit, but if you're interested, see https://en.wikipedia.org/wiki/Singleton_pattern.
Summary
- Static methods use the static keyword.
- Static methods are methods that you can call without having to create an object of the class that provides the method.
- To call a static method, use the name of class, followed by the scope operator
::, followed by the method name. - Static methods are often used for utility functions and for the singleton code pattern.