Singleton Pattern
Implementing the singleton pattern in PHP
1 min read |113 words
March 13, 2026Singleton Pattern
The singleton pattern ensures a class has only one instance.
class Database
{
private static ?self $instance = null;
private function __construct(
private readonly PDO $pdo
) {}
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self(
new PDO('mysql:host=localhost;dbname=app', 'root', '')
);
}
return self::$instance;
}
public function query(string $sql): array
{
return $this->pdo->query($sql)->fetchAll();
}
}
Related Posts
PHP Array Functions
Essential PHP array functions and patterns
phpbackendarrays
PHP References (&)
Useful PHP reference snippets and patterns
phpbackend
For Looping in Python
Using for loops to manipulate arrays in Python.
pythonbackendarrays
While Looping in Python
Using while loops to manipulate arrays in Python.
pythonbackendarrays