title: MongoDB PHP OOP - Error Property of non-object
body: <p>I am trying to use OOP PHP to access my mongodb collection. Yet on the page it returns nothing, but when I look in my apache error log it states</p>
  
  <blockquote>
    <p>PHP Notice:  Trying to get property of non-object in main.php on line 22</p>
  </blockquote>
  
  <p>Here is the code I'm using:
  db.php</p>
  
  <pre><code>class db {
      static $db = NULL;
  
      static function getMongoCon()
      {
          if (self::$db === null)
          {
              try {
                  $m = new Mongo('mongodb://{user}:{password}@{host}:{port}/{database}');
  
              } catch (MongoConnectionException $e) {
                  die('Failed to connect to MongoDB '.$e-&gt;getMessage());
              }
              self::$db = $m;
          }
              else
          {
              return self::$db;
          }
      }
     }
  </code></pre>
  
  <p>main.php</p>
  
  <pre><code>//load db files
  require_once('db.php');
  
  class test{
     public function __construct() {
         echo $this-&gt;output();
     } 
     public function output() {
         $con=db::getMongoCon();
         $db=$con-&gt;database;
         $test=$db-&gt;collection;
         $n=$test-&gt;find();
         print_r($n);
     } 
  }
  
  new test();
  </code></pre>
  
  <p>This all works using procedural code, and I have been able to insert data in this method as well - so it should work (I have removed the database details here for obvious security reasons).</p>
  
  <p>Note: I have read <a href="https://stackoverflow.com/questions/9990799/how-to-connect-to-mongodb-from-another-php-class">this</a> but it is still not working.</p>