How does a Singleton in PHP differ from static classes?
A Singleton in PHP is a design pattern that restricts the instantiation of a class to a single instance. This means that only one instance of the class can exist at any given time. On the other hand, a static class in PHP is a class that contains only static methods and properties, and cannot be instantiated.
class Singleton {
private static $instance;
private function __construct() {
// private constructor to prevent instantiation
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
var_dump($instance1 === $instance2); // true
Related Questions
- How can PHP be used to recognize and prevent users from registering multiple times on a website?
- What are the advantages and disadvantages of using CSV files for data storage and exchange in PHP applications?
- What are some best practices for creating a submit button that adds entries to multiple MySQL tables in PHP?