What is the Singleton design pattern and how can it be implemented in PHP?
The Singleton design pattern ensures that a class has only one instance and provides a global point of access to it. This can be useful when you want to restrict the instantiation of a class to only one object.
class Singleton {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
// Usage
$singleton = Singleton::getInstance();
Related Questions
- How can PHP functions like trim(), strip_tags(), and htmlentities() be used effectively to sanitize user input in form processing?
- How can object-oriented programming principles be applied to improve the structure of PHP code for displaying data?
- What are the advantages of using PHP to dynamically modify HTML elements based on user input?