Search code examples
phpsingletonphp4

singleton pattern in PHP 4


is it possible to create a singleton class in PHP 4?

Right now I have something like http://pastebin.com/4AgZhgAA which doesn't even get parsed in PHP 4

What's the minimum PHP version required to use a singleton like that?


Solution

  • PHP4 and OOP === car without engine (:

    It is possible but impractical.

    Look this sample code:

    class SomeClass
    {
        var $var1;
    
        function SomeClass()
        {
            // whatever you want here
        }
    
        /* singleton */
        function &getInstance()
        {
            static $obj;
            if(!$obj) {
                $obj = new SomeClass; 
            }
            return $obj;
        }
    }