0

I have done a little study on stackoverflow like this question [they talk on OOP perspective] and others. But, none adequately answer my question. I would also like to know the pros and cons of each. What I have now is a DB class as:

class DB extends DBWrapper{
    
    private static $pdo = null;

    public static function getInstance(){
        if(self::$pdo == null){
            self::PDOConnect();
        }
        return self::$pdo;
    }

    private static function PDOConnect(){
        try{
            self::$pdo = new \PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
            self::$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            self::$pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        } catch (\Exception $e){
            die("Database Connection Failed");
        }
    }
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
tika
  • 7,135
  • 3
  • 51
  • 82
  • 6
    I'm tempted to vote for close as duplicate of e.g. [Global or Singleton for database connection?](http://stackoverflow.com/questions/130878/global-or-singleton-for-database-connection), but don't want my gold badge single-vote-close privilege to kick in this time. I believe the `static private` part of the question doesn't matter and it boils down to the general question "singleton or no singleton", and even though there are differences between the languages/runtimes/frameworks/apis I think it's even independent of the php/pdo-instance tag. – VolkerK Nov 29 '15 at 05:57
  • 1
    Unclear question, and at best, too broad. Voted as such. – Drew Nov 29 '15 at 06:11
  • Do you think `global`s are bad? – PeeHaa Dec 01 '15 at 23:25
  • As mentioned in the first comment, if you ever need a second database connection then your class is restrictive in the sense that it doesn't allow it. So I'd lean towards no. – drew010 Dec 01 '15 at 23:31
  • It's all about coupling. The only purpose of a static database connection is to **appear in your code out of nowhere**. Exactly what you should strive to **avoid.** – Your Common Sense Dec 24 '22 at 08:25

0 Answers0