I've suspected for while that PHP singletons are not real singletons, so I did a test. I created the following class:
class MySingleton {
private static $instance;
private function __construct()
{
error_log("I am a new instance of MySingleton. I was instantiated at " . time());
}
private function __clone(){}
public static function getInstance()
{
if(!is_object(self::$instance)) {
self::$instance = new MySingleton();
}
return self::$instance;
}
}
Next I created a file called test.php:
require('MySingleton.php');
$foo = MySingleton::getInstance();
$bar = MySingleton::getInstance();
$baz = MySingleton::getInstance();
When I run the test.php script on my localhost I get one entry in the Apache error log, which makes it seem like it does what it's supposed to. However, each time I refresh the page in the browser I get another entry in the error log, which means PHP is instantiating a new object.
Is there something I can do differently to make this class return a persistent single-instance of the object? (ie what s singleton is supposed to do).
Please do not respond with all the reasons why you think singletons are bad. I am already familiar with those talking points.
Thanks in advance!
PHP is stateless. On every request, the application is built up and torn down. That being the case, your singleton is instantiated exactly once during the entire course of the application -- that is, once per request.
Contrast that with something like Java, where you have a server, like Tomcat or Jetty, that keeps objects loaded into memory. In this situation, your singleton would survive multiple requests... Until the server is restarted.
In PHP singleton objects live until the script lives. What happens here is once your request finishes, script dies. And for the second request, it creates a new instance of the script hence a new MySingleton object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With