Alex
Alex

Reputation: 68492

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?

Upvotes: 1

Views: 568

Answers (4)

gus
gus

Reputation: 785

You could also use a wrapper function like so;

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

Upvotes: 2

user744116
user744116

Reputation:

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

Upvotes: 2

ern0
ern0

Reputation: 3172

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.)

Upvotes: 1

David Fells
David Fells

Reputation: 6798

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.

Upvotes: 2

Related Questions