How does the use of static::$instance differ from new static() in PHP?
Using static::$instance allows for the implementation of the Singleton design pattern in PHP, ensuring that only one instance of a class is created and providing a global point of access to that instance. On the other hand, using new static() creates a new instance of the class each time it is called, which does not adhere to the Singleton pattern.
class Singleton {
private static $instance = null;
public static function getInstance() {
if (static::$instance === null) {
static::$instance = new static();
}
return static::$instance;
}
}
class Example extends Singleton {
// Class implementation
}
$instance1 = Example::getInstance();
$instance2 = Example::getInstance();
var_dump($instance1 === $instance2); // Output: true
Related Questions
- What are the best practices for handling duplicate category names in different levels of a directory tree in PHP?
- What are the differences in DSN configuration between MySQL and Oracle databases when using PHP PDO?
- Are there any best practices or recommended steps to follow when setting up MySQL for PHP applications on a Windows platform?