title: PHP MySQL connection sharing between objects
body: <p>I'm trying to work out the best was of having multiple objects in a program connect to a database. </p>
  
  <p>I created an class with a static connection var. This seems to mean that only one connection is opened and all objects share it.</p>
  
  <pre><code>class Database {
      public static $mysql;
      function __construct() {
          if (!isset(self::$mysql)) {
              echo "Make static connection\n";
              self::$mysql = new mysqli("localhost", "gamalert", "c45ualty", "events");
              if (self::$mysql-&gt;connect_errno) {
                  echo "Failed to connect to MySQL: (" . $this-&gt;mysql-&gt;connect_errno . ") " . self::$mysql-&gt;connect_error;
              }
              echo self::$mysql-&gt;host_info . "\n";
          }
      }
  }
  </code></pre>
  
  <p>A normal object version. This creates a new connection for each object that uses it.</p>
  
  <pre><code>class Database {
      public $mysql;
      function __construct() {
          if (!isset($this-&gt;mysql)) {
              echo "Make connection\n";
              $this-&gt;mysql = new mysqli("localhost", "gamalert", "c45ualty", "events");
              if ($this-&gt;mysql-&gt;connect_errno) {
                  echo "Failed to connect to MySQL: (" . $this-&gt;mysql-&gt;connect_errno . ") " . $this-&gt;mysql-&gt;connect_error;
              }
              echo $this-&gt;mysql-&gt;host_info . "\n";
          }
      }
  </code></pre>
  
  <p>I was wondering what the preferred option being? I plan on testing the performance difference later.</p>