This is more a "good coding practice" question, as opposed to a "how do I solve this" question. My general PHP skills are somewhere between beginner and intermediate, and I'm starting on OO PHP.
Suppose I have a database connection class:
Code: Select all
<?php
class database {}
?>
Say I want to manipulate some tables via table-specific classes. According to a beginner's OO PHP tutorial I found somewhere, I'd just extend the database class.
Code: Select all
<?php
class database {
public function connect () {}
}
class tableA extends database {}
class tableB extends database {}
$useA = new tableA ();
$useB = new tableB ();
$useA->connect();
$useB->connect();
?>
If I'm understanding this correctly, $useA and $useB create their own connections to the database. This is fine if I have connections to spare. If, on the other hand, I'm sharing a database with several other departments, all of whom have their own coding volunteers with their own ideas of good practice, I might only get a couple connections before the database starts refusing...
So, suppose I only get one connection per execution/web page access? Aside from using disconnect() every chance I get, what is the best practice for having the two classes share a connection? Can I feed the connection object as an argument when I create the instances of the table classes? Something like this:
Code: Select all
<?php
class database{}
class tableA {
private $cxn;
function __construct ($db) {
$this->cxn = $db;
}
}
class tableB {
private $cxn;
function __construct ($db) {
$this->cxn = $db;
}
}
$db = new database();
$useA = new tableA ($db);
$useB = new tableB ($db);
Thanks!
dafydd
--
The word "instantiate" bugs me. "Create an instance of" is too hard to type?