Recently i wrote a code example for using the singleton pattern in PHP 5, and have had several people ask if there was a way to do it in PHP 4. After some research i found that there is in fact a way to do this.
In PHP 4 you could not have static class properties however you can have static variables in a function. Here is the function you will need to use for your classes.
<?php
function &singleton($class) {
static $instances;
if (!is_array($instances)) {
$instances = array();
}
if (!isset($instances[$class])) {
$instances[$class] =& new $class;
}
return $instances[$class];
}
?>
Notice that i have used the & (reference operator) in the above code, this is so that we pass by reference rather than letting php make a copy of the object.
Now that you have this function you can place that anywhere in your files before you class is called or included. Next we will create an example class.
The above function was sent in by Dan Cech, from the NYPHP Users Group.
The function i had didnt properly deal with more than one class, his does.
He also altered the way it returned the references.
This will return the static instance of the class and will set the values for each class's $test property, then it will echo them to show you that they are different.
Hopefully this has helped a few people and you now understand how to use the singleton pattern in PHP 4.
Please not that a static variable in php 4 is only good on one page load, meaning that if you navigate to another page $instance is no longer set. You will need to add some session handling in here to do this.
I also have another way to do something similar to this without all this singleton stuff that i will touch on.
If you dont want to get too involved in patterns with php 4 (which i dont think you should do anyway) there is a very simple way to achieve the above.
I have this in a file called global.php and i include the global file in all of my files
<?php
include('class/Cart.php');
session_start();
if ((!isset($_SESSION['cart'])) || (!is_object($_SESSION['cart']))) {
$_SESSION['cart'] = new cart;
} else {
$cart = &$_SESSION['cart'];
}
?>
this code will store the object in a session variable and it will only load a new object if the session object is not found.
basically the same results as above for php 4.
Notice i have have my class file included before the session_start(); In order for this to work you MUST have all classes that you will be storing in a session before the session_start().