dsu89430 2014-09-28 03:11
浏览 30
已采纳

多个数据库连接(不需要的)

i am trying to get to grips with OOP a little better.

i am using this __construct method wthin all my class files This is functioning fine, and as expected

private $conn; // database connection

// make database connection if not exist!
function __construct() {
    // autoload class files
    require_once('class/autoloader.php'); 
    spl_autoload_register('myAutoloader');

    // open db connection so it is available to all files
    $db = new dbconn();
    $this->conn = $db->get_connection();        
}

However, i have multiple class files that all reference eachother, so as the database connection is being loaded into all class files does this mean i am opening too many connections. AND do i need to close each instance of the connection? (if so this is tricky as i dont always know what class files may have been initiated).

I would be grateful for any advice!

  • 写回答

2条回答 默认 最新

  • doufang8965 2014-09-28 03:19
    关注

    The code above does not give enough context to answer if anything is actually wrong.

    Some things to keep in mind.

    the __construct function will get called anytime you create a new instance of this class. If you only create one instance of this class and share the instance with any of the other classes you are using, you will be fine.

    // Use DI to pass in the database connection.
    function __construct($dbConn) {
        $this->conn = $dbConn;        
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题