Page 1 of 1
Accesing class var from different class
Posted: Sat Oct 21, 2006 10:36 am
by RecoilUK
Hi guys
Is it possible to access an object of one class, from inside another class?
Bascially I have a dbconnect class, I start this iwth ...
$db = new dbconnect();
Now I have a form class, in this I want to access the dblink which is the mysql connection ...
$db->dblink;
I thought this would be possible but cant get it to work for some reason.
Is it possible?
Thx
Posted: Sat Oct 21, 2006 10:50 am
by s.dot
What errors is it giving you?
It is definately possible. Make sure you require() the class before you try to instantiate it.
Posted: Sat Oct 21, 2006 10:59 am
by RecoilUK
Hi
Thx for the reply
Here is the class construct that creates the link ...
Code: Select all
function __construct() {
$this->db_link = @mysqli_connect ($this->db_host, $this->db_user, $this->db_pass, $this->db_dbname);
if (!$this->db_link) {
exit ("Error - Database seem's to be malfunctioning");
}
}
and my session_handler should see the link ...
Code: Select all
function _open($path, $name) {
$this->sess_link = $db->db_link;
if (!$this->sess_link) {
exit ("Error - sessions seem to be malfunctioning");
}
return TRUE;
}
This is the error i,m getting
Notice: Undefined variable: db in D:\htdocs\classes\session_handler.php on line 30
Notice: Trying to get property of non-object in D:\htdocs\classes\session_handler.php on line 30
Error - sessions seem to be malfunctioning
Thx again
Posted: Sat Oct 21, 2006 4:08 pm
by jmut
well generally there are to approaches to this one.
Code: Select all
//add $db to global scope..so you see it withing function....bad stuff.
function _open($path, $name) {
global $db;
$this->sess_link = $db->db_link;
if (!$this->sess_link) {
exit ("Error - sessions seem to be malfunctioning");
}
return TRUE;
}
//add as param. recommended
function _open($path, $name,$db) {
$this->sess_link = $db->db_link;
if (!$this->sess_link) {
exit ("Error - sessions seem to be malfunctioning");
}
return TRUE;
}
besides these two..you can use a registry class to store the object...and use it anywhere after that...kind of like the global stuff...but not quite

Posted: Sat Oct 21, 2006 5:59 pm
by Chris Corbyn
You can also set $db as a property in session_handler so it can re-used.