My Singleton

If you have not come across design patterns, they are well worth reading up on. There is a great overview for PHP developers at IBM.

Below is a code snippet that I use for creating singleton objects. Anytime I need to reference the database I call db() which returns a database object, creating the object if this is teh first time it has been called.

This method is not Object Oriented in any way, but it works very well for my needs. The fw_database object is part of my own framework.

function db() {
    static $__db;
    
    if (!is_object($__db)) {
      $__db = new fw_database(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    }
    
    return $__db;
}

The fw_database object is part of my own framework.