1

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?

Alex
  • 66,732
  • 177
  • 439
  • 641
  • Why do you need this in PHP 4 in the first place? It is really, really dead. Building new software based on it is a really bad idea. – Pekka May 11 '11 at 12:28

4 Answers4

2

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.

David Fells
  • 6,678
  • 1
  • 22
  • 34
2

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;
    }
}
Wiseguy
  • 20,522
  • 8
  • 65
  • 81
2

You could also use a wrapper function like so;

 function getDB() {
   static $db;
   if($db===NULL) $db = new db();
   return $db;
 }
gus
  • 765
  • 3
  • 14
  • 26
1

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

ern0
  • 3,074
  • 25
  • 40
  • "PHP4 don't support inheritance" - Sorry, old post, but what is meant by this statement? PHP4 certainly does/did support "inheritance"? – MrWhite Dec 31 '15 at 21:35