Classes and extending classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Classes and extending classes

Post 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.
User avatar
andre_c
Forum Contributor
Posts: 412
Joined: Sun Feb 29, 2004 6:49 pm
Location: Salt Lake City, Utah

Post 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
Post Reply