PHP4.3+ Singleton Class

While working on a PHP project, I really needed a singleton class. All of the artcles I found online about singletons in PHP4, used a non-member function. This just seems like a big mess to me. I want to be able to use it like a static member in C++. My other requirement was the ability to store the instance across the session, if the session was started. I came up with the following member that you can add to any PHP 4.3+ class...
function & singleton()
{
    $inst_name = "_INSTANCE_" . strtoupper(__CLASS__);
    if (isset($_SESSION))
    {
        if (!isset($_SESSION[$inst_name]))
            $_SESSION[$inst_name] =& new Cart();
        return $_SESSION[$inst_name];
    }
    else
    {
        if (!isset($GLOBALS[$inst_name]))
            $GLOBALS[$inst_name] =& new Cart();
        return $GLOBALS[$inst_name];
    }
}
If this member was added to a class named "Logger", you would get a refernce to the instance like so...
$logger =& Logger::singleton();

Trackback URL for this post:

http://www.techsanctuary.com/trackback/5

de goedkope speelgoed winkel

de speelgoedwinkel met goed en goedkoop speelgoed!