使用Singleton类在php中建立数据库连接 [英] Establishing database connection in php using singleton class
本文介绍了使用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.
这篇关于使用Singleton类在php中建立数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文