4
我希望能够从print_r隐藏我的数据库连接,所以我使用了一个静态变量。我有一个基类和一些对象类。理想情况下,他们都将共享相同的数据库连接。什么是分享这个最好的方式? 我现在设置的方式“有效”,但它感觉不对。必须是一个更好的方式来做到这一点。 (逻辑类不应该继承彼此)在类之间共享数据库连接的最佳方式
class base {
private static $db;
function __construct() {
self::$db = new DB(); // our database class
$foo = new Foo(self::$db); // some other class that needs the same connection
}
}
class Foo {
private static $db;
function __construct($db) {
self::$db = $db;
}
}
构造函数应该是私有的,以确保没有多于一个类的实例。 – binaryLV 2011-04-08 14:24:47
是的,我忘了提及=)谢谢。 – Headshota 2011-04-08 14:25:29
感谢您的建议!已经实现了Singleton模式,它运行良好。 – aaronfarr 2011-04-08 15:06:08