How to create an object in a parent class shared b

2019-08-20 08:33发布

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.

标签: php class object
2条回答
SAY GOODBYE
2楼-- · 2019-08-20 08:39

You could make $db static I suppose.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-20 08:58

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);
查看更多
登录 后发表回答