TopicObserver.com

Trond Pettersen on Web Development and Topic Maps

Tag: singleton

PHP is not Java but Java is not a Singleton

In a reply to my twitter rant about PHP’s lack of method overloading a while ago, I was pointed to PHP Advent 2008 / PHP is not Java by Luke Welling. The post discusses how PHP code may turn unnecessary complex by applying Java-style design to PHP code. Well, it tries to.

The point of the article is valid: you should definitively make use of the language’s built-in features instead of inventing your own. It uses a very bad example, though, and that’s what this rant is all about. Now, I am very late to the party here, but still want to point out the misconception.

Welling wrote:

In case you are not familiar with it, the singleton pattern is a general solution to many situations where you want only one instance of a particular class. [...]

class Singleton
{
    private static $myObject;

    private function Singleton()
    {
        // Providing a constructor to eliminate default public one.
    }

    public static function getInstance()
    {
        if (! isset(Singleton::$myObject) )
        {
            Singleton::$myObject = new MyObject();
        }

        return Singleton::$myObject;
    }

    private function __clone()
    {
    }
}

True.

An experienced PHP developer is much more likely to implement the same pattern as follows:

global $myObject;

if (!isset($myObject)) {
    $myObject = new MyObject();
}

False.

An experienced PHP developer would know that the Singleton pattern could still be used because it makes sure you only create 1 instance of the MyObject class. In Luke Welling’s example, you would always have to remember to check if there was an existing instance of $myObject available, else you’d end up with more than 1 instance of the class. Even worse: what if $myObject was not set, but MyObject had already been instantiated somewhere in your code? $myOtherObject, for instance? You could end up with $stillAnotherObject. More than 1 database connection, etc.

Hence, the experienced PHP developer would make use of the Singleton pattern, and do this instead:

global $myObject;

if (!isset($myObject)) {
    $myObject = Singleton::getInstance();
}

Or just

$myObject = Singleton::getInstance();

He’d then rest assured that even if MyObject had already been instantiated, $myObject would now reference the single instance.

(And I am still annoyed by the lack of method overloading in PHP5.x — it’s just stupid!)

  • RSS @twitter

  • Tags

  • Topics

  • Recent Comments

  • Topic Map Feeds