使用Singleton类在php中建立数据库连接

问题描述:

任何人都可以通过示例代码指导我,以使用Singleton类在php中建立数据库连接.

Can anybody please guide me with a sample code to establish a database connection in php using singleton class.

class DatabaseSingleton
{
  // [Singleton]
  private static $instance = null;
  public static function getInstance()
  {
    if (!self::$instance)
    {
      self::$instance = new self();
    }
    return self::$instance;
  }
  private function __clone(){}
  // [/Singleton]

  private $connection = null;

  private function __construct()
  {
    $this->connection = mysql_connect('localhost','root','admin');
    if ($this->connection)
    {
      mysql_select_db('my_database');
    }
  }

  //
  // crud operations go here.
  //
}

$db = DatabaseSingleton::getInstance();
$db->SomeCRUDOperation();

也许是这样的事情?很基本,但是应该给您一个起点.

Something like that perhaps? Very basic, but should give you a starting point.