Page 1 of 1

passing an database object to a class

Posted: Tue Apr 24, 2012 7:24 am
by php3ch0
OK so I am starting in the world of OOP and I have the need to query the database from another class from the database one. This is the code I have so far

page.inc.php (where I include files etc and create the $db object)

Code: Select all

require_once("db.class.php"); //the db class

$db = new DB($g_db, "localhost", $g_dbuser, $g_dbpass);

require_once("user.inc.php");

$user = new user($_SESSION['uid']);

The user.inc.php class (this is where the error is)

Code: Select all

class user {
	

	var $uid; // Database object
	protected $dbo; 
		
	public function __construct(&$db) { 
		$this ->dbo = &$db; 
		}

	function signin($uid) {
			$userdata = $this->dbo->query_UniqueObject("SELECT * FROM users WHERE id = '$uid'");
			$_SESSION['uid'] = $userdata->id;
			$_SESSION['al'] = $userdata->access_level;
			session_write_close();
			}
}
This is the error I am getting: Fatal error: Call to a member function query_UniqueObject() on a non-object in /home/combatli/public_html/includes/user.inc.php on line 14

I know I can declare $db as a global but I want to avoid it (even tried it and cannot get it to work) by adding it after here function signin($uid) { global $db; Any help would be appreciated.

Re: passing an database object to a class

Posted: Tue Apr 24, 2012 8:39 am
by x_mutatis_mutandis_x
$this->dbo is not being set because you are passing a string ($_SESSION['uid']) instead of $db from page.inc.php. Your class user accepts a DB object in the constructor

Code: Select all

public function __construct(&$db) { 
                $this ->dbo = &$db; 
                }
 
So, change page.inc.php:

Code: Select all


require_once("db.class.php"); //the db class
 
$db = new DB($g_db, "localhost", $g_dbuser, $g_dbpass);
 
require_once("user.inc.php");

//$user = new user($_SESSION['uid']);
$user = new user($db);
 

Re: passing an database object to a class

Posted: Tue Apr 24, 2012 10:26 am
by php3ch0
Hello I have changed this but still getting the same error. Any other suggestions?

Re: passing an database object to a class

Posted: Tue Apr 24, 2012 11:20 am
by pickle
You've got a space in here: $this ->dbo, maybe that's causing it. Other than that, check in the constructor of User to see if $this->dbo is being set properly.

Also, if you're using PHP5, you don't need to to = &$db, as objects are assigned by reference by default.