mausie Posted July 22, 2007 Share Posted July 22, 2007 Hi all, I’m rewriting a script of mine into PHP5 OOP. Even tho I have some difficults finding a good way. I have a Class for database connections/functions (clsDB) and a Class for Statistics (clsStats) So my question is, what’s the best way to use the DB functions within the Stats class? My main code says: $objDB = new clsDB(‘host’,'user','pass','db'); $stats = new clsStats(); In my clsStats class there are alot of functions that use queries. They have to go through clsDB and if you ask me, through $objDB. (That makes sense to ME) But I can't access $objDB from my Stats class. Which is pretty logic caus it ain’t a member variable within that class. I can use a __constructor on clsStats so I pass the $objDB into the Stats object I’ll create. That would look like this: $objDB = new clsDB(‘host’,'user','pass','db'); $stats = new clsStats($objDB); But I can’t access any function through $this->objDB->function(); then. It just doesn’t recognize it anymore. Even when I only pass the memory (&). I could make my Database Class Static. But that makes no sense if you ask me. Because I would use query functions whit out using a object which has all the connections in it. Could you guys and girlie's help me with this? Thanks! Link to comment https://forums.phpfreaks.com/topic/61218-database-class-within-a-other-class/ Share on other sites More sharing options...
Barand Posted July 22, 2007 Share Posted July 22, 2007 this works <?php class db { private $connection; private $dbname; function __construct ($h, $us, $pw, $db) { $this->connection = mysql_connect($h, $us, $pw); $this->dbname = $db; mysql_select_db($db); } function show_tables() { $res = mysql_query("SHOW TABLES FROM $this->dbname") or die(mysql_error()); while ($row = mysql_fetch_row($res)) { echo $row[0], '<br>'; } } } class stats { private $db; function __construct($dbObj) { $this->db = $dbObj; } function list_tables() { $this->db->show_tables(); } } $db = new db ('localhost','','','test3'); $stat = new stats($db); $stat->list_tables() ?> Link to comment https://forums.phpfreaks.com/topic/61218-database-class-within-a-other-class/#findComment-304589 Share on other sites More sharing options...
mausie Posted July 22, 2007 Author Share Posted July 22, 2007 Damn. I forgot $this on: $this->db = $dbObj; Feel so stupid :'( Thank you! Link to comment https://forums.phpfreaks.com/topic/61218-database-class-within-a-other-class/#findComment-304604 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.