0

I am a beginner when it comes to working with OOP PHP and I would like to know how to properly close a database connection in OOP PHP. I have seen similar questions but none of the answers helped. Here is how I connect to the database:

<?php

class Db {

    private $host = "localhost";
    private $user = "root";
    private $pwd = "";
    private $dbName = "database";

    protected function connect() {
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbName;
        $pdo = new PDO($dsn, $this->user, $this->pwd);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        return $pdo;
    }

}

So, how would I close this connection?

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
Looky1173
  • 440
  • 6
  • 17
  • : "It looks like you're writing your own ORM. Have you considered using one that's already written, tested, and widely supported like [Atlas](http://atlasphp.io), [Doctrine](http://www.doctrine-project.org/),  or [Eloquent](https://laravel.com/docs/master/eloquent)?" – tadman Dec 19 '20 at 09:05
  • 1
    You don't need to do anything special. If a variable falls out of scope it'll be cleared up soon enough. Normally you want to have a database connection pool, anyway, so you're not constantly connecting, which can be a real performance drag. – tadman Dec 19 '20 at 09:05
  • Note: This isn't an "OOP" problem per-se, it's a general connection handling strategy thing. – tadman Dec 19 '20 at 09:06
  • 2
    This is how you shouldn't connect to a database in the first place. Many important options are missing, while the code present suggests a misuse. Given you MUST call the connect() function only ONCE per script execution, it questions the entire class existence. Please read my article on the [common database wrapper mistakes](https://phpdelusions.net/pdo/common_mistakes) and check out the [proper PDO connection code](https://phpdelusions.net/pdo_examples/connect_to_mysql). – Your Common Sense Dec 19 '20 at 10:02

0 Answers0