Pages

Categories

The basics of singletons in PHP4 & 5

A singleton is nothing more than a class you can’t instantiate multiple times. Actually, I just lied ;) In PHP4 you can instantiate your class multiple times but if you do that you’re not using it as a singleton.

At first it may be easy to get carried away with where you should use them and where you should not. I generally stick with the rule that if you have a layer in an application which you use repeatedly but have noticed you keep instantiating it in various points then you should be using a singleton. Some people don’t like them which is of course personal preference but learning how to use them can prove incredibly useful. One of the most common implementations of a singelton would be a database object which you use through your application… the lack of re-instantiation takes out an amount of overhead in addition to ensuring all parts of the application have full communication with the same object (which of course can have a bad effect if used wrongly!).

The way you work with singletons differs slightly between PHP version 4 and PHP5. This is mostly due to the way PHP5 handles class properties and static variables better than PHP4. Here we’ll take a look at the two methods alongside each other.

First, the PHP5 version:

<?php

/*
 An example of a singleton using PHP5
 – d11wtq @ w3style
 */

class singleton
{

    static private $instance = null;
    private function __construct()
    {
        //Notice this is declared private so now we cannot
        // use the "new" keyword from outside the class
    }

    static public function getInstance()
    {
         if (self::$instance == null) //Not instantiated yet
        {
            //The class can run the private constructor
            self::$instance = new singleton();
        }
        return self::$instance;
    }

}

$obj = singleton::getInstance()//Ask for the object statically

?>

As you can see, we’ve made a very valid use of the available keywords in PHP5/OOP. We declare our constructor as private so that we would get a fatal error if we attempt to instantiate the singleton class using $obj = new singleton(); . The class holds an instance of itself statically, and it checks for the presence of this instance upon the execution of the getInstance() method which we call statically.

Now let’s look at the PHP4 version:

<?php

/*
 An example of a singleton using PHP4
 – d11wtq @ w3style
 */

class singleton
{

    function singleton
    {
        //Unlike with PHP5 we can’t really prevent this being run without
        // manually throwing an exception
    }

    //We need the reference operator since
    // PHP4 does not pass objects by reference by default
    function &getInstance()
    {
         static $instance; //Declare the static variable inside the static method!
         
         if (!$instance) //Not instantiated yet
        {
            //Hmm… we use an array!
            $instance = array( new singleton() );
        }
        return $instance[0]; //… and we return it’s first element
    }

}

//Ask for the object statically, and as a reference
$obj =& singleton::getInstance();

?>

I bet you’re thinking the same as me. PHP5 makes it much simpler to work with singletons, it also provides the added constraints developers might expect in an OOP environment.

The first big difference is that we can’t reasonably prevent the use of the constructor in PHP4 classes. Secondly, static variables are handled in a much more ad-hoc fashion. And lastly, PHP4 does not pass objects by-reference as a default so we need to explicitly ask it to.

This entry was posted on Tuesday, April 4th, 2006 at 10:26 pm and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “The basics of singletons in PHP4 & 5”

  • Stephen [ 03Oct07]

    I tend to use the syntax:

    self::$instance = new self();

    instead of

    self::$instance = new singleton();

    That way the class doesn’t really care what it’s called. One less chance of a typo!

    Enjoying the examples

    S

Leave a Reply







XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>