将类存储在类变量中我做得对吗?.PHP


Storing a class in a classes variable am I doing it right? PHP

我目前正在这样做,

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但意识到无法将扩展类提取到变量中?

谢谢

你非常接近依赖关系注入设计模式。

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

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

然后使用数据库连接实例化您的类,如下所示:

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

这具有多种好处,从更易于测试到与数据库建立单个连接。假设您需要五个Page对象 - 现在您向它们传递相同的数据库连接,这样它们就不需要单独创建一个。

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