Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

singleton

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!

like image 894
Neil Girardi Avatar asked Nov 30 '22 03:11

Neil Girardi


2 Answers

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.

like image 179
Thomas Kelley Avatar answered Dec 04 '22 03:12

Thomas Kelley


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.

like image 37
lloydh Avatar answered Dec 04 '22 05:12

lloydh