Question

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?

Était-ce utile?

La 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;
    }
}

Autres conseils

Alex, this article should be helpful - http://abing.gotdns.com/posts/2006/php4-tricks-the-singleton-pattern-part-i/ . The key is to use a base class, and in the child class constructor, invoke the parent's singleton instantiation method.

You could also use a wrapper function like so;

 function getDB() {
   static $db;
   if($db===NULL) $db = new db();
   return $db;
 }

When you programming in a language which is not strict OOP, it's easy to use the dark side of the force:

function getInstance() {
  global $singleObj;

  if (!is_object($singleObj)) $singleObj = new Foo();
  return $singleObj;
}

And why not? Looks uglier than a strict singleton? I don't think so.

(Also, don't forget that PHP4 don't support inheritance - I've spent some hours with it.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top