title: Is it a best practice always keep database connection in a single instance?
body: <p>I want to ask whether is good practice to have single instance of database connection or declare new every times when we needed? I have this two designs shown in below:</p>
  
  <p><strong>This is database class:</strong></p>
  
  <pre><code>&lt;?php
  class Database extends PDO {
      //Variable declaration
      private $host = "localhost";
      private $passwd = "";
      private $username = "root";
      private $dbname = "";
  
      //Connect to DB when the class construct
      public function __construct($host=NULL, $dbname=NULL, $username=NULL, $passwd=NULL) {
          if(isset($host) &amp;&amp; !empty($host)) {
              $this-&gt;host = $host;
          }
  
          if(isset($dbname) &amp;&amp; !empty($dbname)) {
              $this-&gt;dbname = $dbname;
          }
  
          if(isset($username) &amp;&amp; !empty($username)) {
              $this-&gt;username = $username;
          }
  
          if(isset($passwd) &amp;&amp; !empty($passwd)) {
              $this-&gt;passwd = $passwd;
          }
  
          parent::__construct("mysql:dbname=$this-&gt;dbname;host=$this-&gt;host", $this-&gt;username, $this-&gt;passwd, NULL);
          parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          parent::setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      }
  
  }
  ?&gt;
  </code></pre>
  
  <p><strong>Method 1 : Dependency Injection</strong></p>
  
  <pre><code>&lt;?php
  class User {
      private $db;
  
      public function __construct(Database $db) {
          $this-&gt;db = $db;
      }
  
      //Some update and insert below here
  }
  
  class Employee {
      private $db;
  
      public function __construct(Database $db) {
          $this-&gt;db = $db;
      }
  
      //Some update and insert below here
  }
  ?&gt;
  </code></pre>
  
  <p>So, I will do this when I want to use the classes:</p>
  
  <pre><code>&lt;?php 
      $db = new Database();
  
      $user = new User($db);
      $user-&gt;update($id,$data);
  
      $emp = new Employee($db);
      $emp-&gt;delete($id);
  ?&gt;
  </code></pre>
  
  <p>or the other ways?</p>
  
  <p><strong>Method 2:</strong></p>
  
  <pre><code>&lt;?php
  class User {
      private $db;
  
      public function __construct() {
          $this-&gt;db = new Database();
      }
  
      //Some update and insert below here
  }
  
  class Employee {
      private $db;
  
      public function __construct() {
          $this-&gt;db = new Database();
      }
  
      //Some update and insert below here
  }
  ?&gt;
  </code></pre>
  
  <p>and when I want to use it I will:</p>
  
  <pre><code>&lt;?php  
      $user = new User();
      $user-&gt;update($id,$data);
  
      $emp = new Employee();
      $emp-&gt;delete($id);
  ?&gt;
  </code></pre>
  
  <p>Which method is preferable or better? Offer an explanation if possible.</p>