如何将单个MySql连接与多个PHP对象一起使用. [英] How do I use a single MySql connection with multiple PHP objects.
本文介绍了如何将单个MySql连接与多个PHP对象一起使用.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在浏览许多示例,但是阅读的次数越多,我就会感到困惑(对不起!).我的首要任务是保持其简单高效.生成一个MySql连接,并与多个PHP对象共享它.
I have been going through lots of examples on this, but the more I read the more I get confused (sorry!). My priority is keep it simple and efficient. Generate a single MySql connection and share it with multiple PHP objects.
// open a db connection
$dbc = new PDO(.......);
// allow multiple objects to use the same connection
$object_1 = new class_1($dbc);
$object_2 = new class_2($dbc);
$object_3 = new class_3($dbc);
// or should it be passed this way?
$object_1->connection($dbc);
$object_2->connection($dbc);
$object_3->connection($dbc);
// or should each of the classes be getting the connection
// from a singleton type db object?
// should each object be an extesion of a db class?
// or is there something else I need to consider?
推荐答案
我倾向于将Connection Class命名为Singlton:
I preffer to make Connection Class as Singlton :
class DBConnection {
// Store the single instance of DBConnection
private static $m_pInstance;
private function __construct() { ... }
public static function getInstance()
{
if (!self::$m_pInstance)
{
self::$m_pInstance = new DBConnection();
}
return self::$m_pInstance;
}
}
这篇关于如何将单个MySql连接与多个PHP对象一起使用.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文