MongoDB PHP OOP - Error Property of non-object -
this question has answer here:
i trying use oop php access mongodb collection. yet on page returns nothing, when in apache error log states
php notice: trying property of non-object in main.php on line 22
here code i'm using: db.php
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 connect mongodb '.$e->getmessage()); } self::$db = $m; } else { return self::$db; } } }
main.php
//load db files require_once('db.php'); class test{ public function __construct() { echo $this->output(); } public function output() { $con=db::getmongocon(); $db=$con->database; $test=$db->collection; $n=$test->find(); print_r($n); } } new test();
this works using procedural code, , have been able insert data in method - should work (i have removed database details here obvious security reasons).
note: have read this still not working.
it's simple mistake. you're using factory pattern, first time you're calling getmongocon
method, it'll return null:
class db {//convention: upper-case classes private static $_db = null;//using pattern public static bad idea public static function getmongocon() {//^^ best specify public/private/protected if (self::$db === null) {//first time called: true try { //i'd assign immediatly here, hey... self::$db = new mongo('mongodb://{user}:{password}@{host}:{port}/{database}'); $m = new mongo('mongodb://{user}:{password}@{host}:{port}/{database}'); } catch (mongoconnectionexception $e) { die('failed connect mongodb '.$e->getmessage()); } self::$db = $m; } //!!leave out else fix!! return self::$db; } }
as can see, did leave out else, no matter value of self::$db
was have return it. if was null, you'll never in else
branch, contained return statement.
there no real reason throw-catch
block. rely on db-connection code work, if doesn't just, there no backup afaik, let throw (and halt).
just completeness, here's how i'd write above code:
class db { private static $_db = null; public static function getmongocon($new = false) {//allow connection, never know... if (self::$_db === null) { self::$_db = new mongo('mongodb://{user}:{password}@{host}:{port}/{database}'); } if (true === !!$new) { return new mongo('mongodb://{user}:{password}@{host}:{port}/{database}'); } return self::$_db; //or, short 'n messy: return (!$new ? self::$_db : new mongo('mongodb://{user}:{password}@{host}:{port}/{database}')); } }