Singletons in PHP4


Uno, Dos, Tres.


Not everybody is developing on PHP5 these days, even though PHP4 is no longer supported *yikes!*

And these people (namely me) need a way to implement the Singleton pattern.

The Singleton pattern is single-handedly the single most useful pattern when you only ever want to have one instance of a class instantiated at any one time.

Now that we’ve had a few years getting used to using the Singleton pattern (in PHP4) I’d like to summarise the best resources we have on the different ways to implement the Singleton.

Storing Singleton Class in $_SESSION PHP4

The best resource I came across for achieving a persistent Singleton class using the $_SESSION array is found at Tech Sanctuary - Singleton Class.

Just be warned that you must include a reference to the class before you issue session_start(); otherwise you will get a PHP_Incomplete_Class Errror. Eg:

require_once 'singleton.php';
session_start();

To use the Singleton, you would simply do this:

$singleton =& Singleton::getInstance();
$singleton->doMyLaundry();

Pretty cool huh?

For the Classic PHP4 Singleton read this article at WeberDev for an introductory look at the Singleton pattern.

Ideally you’ll want to read the discussions at php.net relating to Object Oriented Programming in PHP4 for a deeper understanding of what’s really going on.


Filed in Nerd musings | Tags: , , ,

Leave a Reply