Singleton pattern with PHP

Sometimes you need only one instance of your class. For example it can be usefull to create only one instance of your database access class and use it everywhere in application. This will reduce memory usage and prevent you from having more than one database connection.

So, your class should look like bellow:

final class Database
{
    private static $instance;
   
    private function __construct()
    {
        // this code will never happen
    }
   
    public static function getInstance()
    {
       if (!isset(self::$instance)) {
           $class = __CLASS__;
           self::$instance = new $class;
       }   
       return self::$instance;
    }
   
    public function __clone()
    {
       trigger_error(‘It is impossible to clone singleton’, E_USER_ERROR);
    }
   
}

This class is defined like final to prevent extentding, usualy people forget about it. It is not a good idea to extend singleton classes because of static members. But if you’ll do this, you also should redefine getInstance() method and $instance member.

3 Responses to “Singleton pattern with PHP”

  1. on 30 Nov 2006 at 9:22 pm Graymur

    А параметры в него как будешь передавать?

  2. on 01 Dec 2006 at 2:47 pm Andrew Dashin

    А какие параметры тебе нужны? Для создания подключения к базе много параметров не надо, и их вполне можно дефайнить. Мне кажется в твоём mysql-враппере так и есть. Во всяком случае так есть во всех что я видел.

  3. on 20 Dec 2006 at 8:10 pm graymur

    А если из одного скрипта к нескольким базам надо?

Trackback this Post | Feed on comments to this Post

Leave a Reply