Page 1 of 1

Classes and extending classes

Posted: Tue May 10, 2005 9:07 pm
by Stryks
Hi, I have a database class I use to connect and handle all of my data in my app and that all works fine.

I have just made a second class for calculating costs and values. The trouble is that this class also accesses the database.

I'm wondering what the best way is to make these classes work together. All of my pages rely on sessions, and they are stored in the database with custom routines, so my database class is running as $db in the background before I even get started with other code.

While I *could* just get the functions which use the database to refer to a global $db; I am wondering if perhaps I should make a new instance of the database class, specifically for the new one, or if perhaps this is the reason for the whole 'extends' idea.

Just after some advice really. Anything would be great.

Posted: Tue May 10, 2005 11:41 pm
by andre_c
i would probably do something like this:

Code: Select all

<?

class Calculator {
  private $db;

  public funciton setDb( Database $db ) {
    $this->db = $db;
  }

  public function someMethod ( $query ) {
    $this->db->query( ... ); // some query
  }
}


$db = new Database;
$calc = new Calculator;

$calc->setDb ( $db );

?>
this creates a reference to the database object, so you're not instantiating a new object (unless you're using php4)

globals are evil, and these classes should not extend each other since their responsibilities are completely different

there isn't any reason to extend the database class either in this situation