pakmannen
08-09-2007, 08:39 AM
Hi
I'm trying to get my head around this with classes. What I'm trying to do is use one class's functions within another class. Probably easier if I just show some code:
class DB
{
var $prefix;
function DB($host, $db_user, $db_pswd, $db_name, $db_prefix)
{
// Connect
$open = mysql_connect($host, $db_user, $db_pswd)
or die('Unable to connect');
$db = mysql_select_db($db_name, $open);
// Set the prefix var
$this->prefix = $db_prefix;
}
}
class Test
{
function hello()
{
return $db->prefix; // Here lies the problem!
}
}
And my index file looks like this at the top:
$db = new DB($host, $db_user, $db_pswd, $db_name, $db_prefix);
$test = new Test();
echo $db->prefix; // Works!
echo $test->hello(); // Does not work!
Now, I can access the DB class just fine, everything works alright with the $db variable etc, but what I don't understand is how I can use DB within my new Test class. The error generated is a "Call to a member function on a non-object" on the row where I try to do this.
Confused!
I'm trying to get my head around this with classes. What I'm trying to do is use one class's functions within another class. Probably easier if I just show some code:
class DB
{
var $prefix;
function DB($host, $db_user, $db_pswd, $db_name, $db_prefix)
{
// Connect
$open = mysql_connect($host, $db_user, $db_pswd)
or die('Unable to connect');
$db = mysql_select_db($db_name, $open);
// Set the prefix var
$this->prefix = $db_prefix;
}
}
class Test
{
function hello()
{
return $db->prefix; // Here lies the problem!
}
}
And my index file looks like this at the top:
$db = new DB($host, $db_user, $db_pswd, $db_name, $db_prefix);
$test = new Test();
echo $db->prefix; // Works!
echo $test->hello(); // Does not work!
Now, I can access the DB class just fine, everything works alright with the $db variable etc, but what I don't understand is how I can use DB within my new Test class. The error generated is a "Call to a member function on a non-object" on the row where I try to do this.
Confused!