I have 4 classes, one Database helper and 3 defined like this:
abstract class PageElement
{
protected $db;
abstract public function reconstruct($from, $params = array());
protected function construct_from_db($id, $k)
{
$this->db = new Database(0);
$query = "SELECT * FROM $k WHERE id = %d";
$results = $this->db->db_query(DB_ARRAY, $query, $id);
return $results[0];
}
}
class Section extends PageElement
{
function __construct($construct, $args = array())
{
$params = $this->construct_from_db($args, 'sections');
}
//other methods
}
class Toolbar extends PageElement
{
function __construct($construct, $args = array())
{
$params = $this->construct_from_db($args, 'toolbars');
}
//other methods
}
Right now, each child has it's own instance of Database object. How can I create the database object in the parent class and share it to each child?
NOTE:
- I've read about the Singleton approach, but I can't use it, since I have to connect to different databases.
- Might be noteworthy that Section class creates an instance of Toolbar class.
Another problem is that, for some reason, I can't close mysql connection. This warning appears when I run the code:
mysql_close(): 7 is not a valid MySQL-Link resource in ****\classes\database.class on line 127.
You could make
$db
static I suppose.Ideally you should create the database object outside these classes and then inject it via constructor or setter function.
Then you can create your objects:
This way all the objects will share same database object.
P.S.: Instead of creating database object using new here, you can get it from a parameterized factory.