【问题标题】:Storing a class in a classes variable am I doing it right? PHP将类存储在类变量中我做得对吗? PHP
【发布时间】:2012-06-14 22:28:47
【问题描述】:

我目前正在这样做,

class Page {
    // variable to hold DBC class
    public $dbc;
    /*
        __CONSTRUCT
        Called when class is initiated and sets the dbc variable to hold the DBC class.
    */
    public function __construct() {
        // set the dbc variable to hold the DBC class
        $this -> dbc = new DBC();
    }
    /*
        CREATE PAGE
        Create a page with the option to pass data into it.
    */
    public function create($title, $class, $data = false) {
        // start buffer
        ob_start('gz_handler');
        // content
        content($this -> dbc, $data);
        // end buffer and flush
        ob_end_flush();
    }

}

我已经简化了示例,但基本上我需要将对象DBC 传递给方法create 内的函数?

这是否被认为是不好的做法,因为我之前使用 extends 但意识到无法将扩展类提取到变量中?

谢谢

【问题讨论】:

    标签: php variables object


    【解决方案1】:

    您非常接近dependency injection 设计模式。

    您只需更改构造函数以接受对象作为参数,如下所示:

    public function __construct( $dbc) {
        // set the dbc variable to hold the DBC class
        $this -> dbc = $dbc;
    }
    

    然后用数据库连接实例化你的类,像这样:

    $dbc = new DBC();
    $page = new Page( $dbc);
    

    这有很多好处,从更容易测试到与数据库建立单一连接。想象一下,您需要五个 Page 对象 - 现在您将所有相同的数据库连接传递给它们,因此它们不需要单独创建一个。

    【讨论】:

    • 啊,好吧,我现在明白了:) 如果没有问题,还有一个问题,但是为什么这种方式比我给出的方式更受欢迎?在课堂内开课或类似的东西是不是很糟糕?谢谢
    【解决方案2】:

    您应该将DBC 类实例传递给构造函数,而不是在其中创建对象。这称为dependency injection:https://en.wikipedia.org/wiki/Dependency_injection

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多