Jump to content

Database class within a other class


mausie

Recommended Posts

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.