PHP OOP〜多类需要相同的类 [英] PHP OOP ~ Multiple Classes Require Same Class

查看:103
本文介绍了PHP OOP〜多类需要相同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有多个类都依赖于一个类,Database类。

I currently have multiple classes that all depend on one class, the Database class. Each class requires an instance of the Database class to function, and with that, I am a little concerned.

在我将所有的程序代码转换为面向对象的代码之前,我需要一个Database类的实例来运行。需要计算出来。我目前有一个数据库连接为整个程序。然而,根据我的理解,当我将我的代码转换为OOP我将有多个类,所有与同一程序内的开放数据库连接。 (所有这些类都将包含在主程序文件中)。

Before I convert all my procedural code to object-oriented code I need to figure this out. I Currently have one database connection for the entire program. However, from what I understand when I convert my code to OOP I will have multiple classes all with open database connections within the same program. (all of these classes will be included in the main program file).

如何正确实现?我假设在同一个程序中有5个打开的数据库连接肯定不是正确的方式。

How do I implement this correctly? I'm assuming having 5 open database connections within the same program is certainly not the correct way.

推荐答案

通过传递数据库连接与构造函数的数据库连接

class Foo {

    private $database = null;

    public function __construct(&$database) {
        $this->database = $database;
    }
}
$connection = mysql_connect(..);
$bar = new Foo($connection);

Singleton

class DatabaseConnection {

    private static $instance = null;

    private function __construct() {
    }

    public static function &getInstance() {
        if (DatabaseConnection::$instance == null) {
            DatabaseConnection::$instance = new DatabaseConnection();
        }
        return DatabaseConnection::$instance;
    }
}

$mysql_query("...", DatabaseConnection::getInstance());

表示通过引用传递,因此即使数据库对象在几个不同的文件,类或函数中使用,也只有一个实例。请参见 http://php.net/manual/en/language.references.pass。 php 了解更多信息。

The & means passing by reference, so there would be only one instance of the database object even if it is used in several different files, classes or functions. See http://php.net/manual/en/language.references.pass.php for more information.

这篇关于PHP OOP〜多类需要相同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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