Why does PHP create a new instance of a singleton each time the script calling Foo::getInstance() is run?

↘锁芯ラ 提交于 2019-12-23 21:00:25

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17560717/why-does-php-create-a-new-instance-of-a-singleton-each-time-the-script-calling-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!