Tivie
Tivie

Reputation: 18923

How to create an object in a parent class shared by its children classes?

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:

Upvotes: 0

Views: 502

Answers (2)

Vikk
Vikk

Reputation: 3373

Ideally you should create the database object outside these classes and then inject it via constructor or setter function.

abstract class PageElement
{
    protected $db;

    function __construct($db)
    {
         $this->db = $db;
    }   
    //...rest of the methods
}

class Toolbar extends PageElement
{
    function __construct($construct, $db, $args = array())
    {
        parent::__construct($db);
        $params = $this->construct_from_db($args, 'toolbars');
    }
    //other methods
}

Then you can create your objects:

$db = new Database(0);
$toolbar = new Toolbar($construct,$db,$args);
$section = new Section($construct,$db,$args);

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.

$db = Factory::getDBO($param);

Upvotes: 3

Mike Thomsen
Mike Thomsen

Reputation: 37506

You could make $db static I suppose.

Upvotes: 0

Related Questions