...

View Full Version : Referencing one class within another



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!

firepages
08-09-2007, 09:13 AM
2 ways, , actually 3 depends on your situation which you will use


<?php
class Test{
function test(&$db){
$this->db=$db;
}

function hello(){
return $this->db->prefix;
}
}
$db = new DB($host, $db_user, $db_pswd, $db_name, $db_prefix);
$test = new Test($db);
echo $test->hello(); // should work
?>

OR you can aggregate the db class within test... though to avoid passing connection parameters around you are better off calling a static instance of your DB class...

<?
class Test{
function test(){
$this->db=new static_instance_of_db();
}

function hello(){
return $this->db->prefix;
}
}
?>

?>
or you can just make $db global :(

google for `singleton` or `static instance` (easier in PHP5 than 4)

pakmannen
08-09-2007, 10:29 AM
Thank you, that first method works great. And I understand it as well! :) Much appreciated.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum