PHP › Design Patterns in PHP
What is the Singleton pattern, and what are its intended use cases along with its commonly cited drawbacks?
BeginnerAnswer
The Singleton pattern ensures a class has only one single instance throughout the application and provides a global point of access to that instance, which is sometimes used for things like a single shared database connection, though it is also commonly criticized for introducing hidden global state that makes testing more difficult and creating tight coupling to that specific class throughout the codebase, leading many modern developers to prefer dependency injection instead for similar use cases.
class Database {
private static ?Database $instance = null;
public static function getInstance(): self {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}Real-world example An older codebase uses a Singleton for its database connection, and a team refactoring that codebase toward better testability replaces it with a properly injected database dependency, immediately making previously untestable classes much easier to test in isolation.