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

    // 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 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;        
    点赞 评论 复制链接分享
  • dongyi1159 dongyi1159 2014-09-28 04:24

    @Ford another thing you could do is create a function that will connect to the database when it is called. This way you do not have your database connection active even when you are not using it. It would allow your scripts to run a little bit faster because you will be calling a resource only when you need it.

    You can also have a close connection function that you will call whenever you are done executing your queries and no longer in need of your DB connection.

    点赞 评论 复制链接分享