如何在由其子类共享的父类中创建对象? [英] How to create an object in a parent class shared by its children classes?

查看:188
本文介绍了如何在由其子类共享的父类中创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个类,一个数据库助手和3这样定义:

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
}

每个孩子都有自己的Database对象实例。如何在父类中创建数据库对象并将其共享给每个孩子?

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?

注意:


  • 我已阅读Singleton方法,不能使用它,因为I
    必须连接到不同的数据库。

  • 可以值得注意的是,Section类创建了一个Toolbar类的实例。

  • 另一个问题是,由于某种原因,我不能关闭mysql连接。当我运行代码时出现此警告:

  • 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不是** * * \\ \\ classes \database.class第127行。

mysql_close(): 7 is not a valid MySQL-Link resource in ****\classes\database.class on line 127.

推荐答案

应该在这些类之外创建数据库对象,然后通过构造函数或setter函数注入它。

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
}

创建您的对象:

$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.

PS:不是使用new在这里创建数据库对象,你可以从参数化的工厂获取它。

P.S.: Instead of creating database object using new here, you can get it from a parameterized factory.

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

这篇关于如何在由其子类共享的父类中创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆