了解PHP继承 [英] Understanding PHP Inheritance

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

问题描述

我了解OOP中继承的基本原理,但是我正在尝试做一件事,希望获得关于如何最好地做到这一点的建议.

I understand the basic principles of inheritance in OOP, but I have a specific thing I am trying to do and want advice on how best to do it.

让我说我有一个核心课程:

Lets say I have a core class:

class Core {
    ....
}

并且我还有2个或更多其他类可以扩展此功能

and I also have 2 or more other classes that extend this functionality

class MyClass1 extends Core {
    ....
}
class MyClass2 extends Core {
    ....
}

,我也有一个数据库类,我在其中执行查询,我想将数据库类的实例化对象(可能是通过引用)传递给我的每个类.这样做的原因之一是要存储该页面在执行时的查询列表或计数.

and I also have a database class in which I perform my queries, I want to pass an instantiated object of the database class (possibly by reference) to each one of my classes. One of the reasons for this would be to store a list or count of the queries that page as executed.

我应该/应该怎么做?

推荐答案

您可以将数据库对象的实例传递给类的构造函数:

You could pass your instance of your database object to a constructor for your classes :

class Core
    protected $db;

    public function __construct(Your_Db_Class $database) {
        $this->db = $database;
    }

}

然后,从您的方法中使用$this->db,以访问您的数据库.

And, then, from your methods, work with $this->db, to access your database.


当然,在实例化类时,必须指定数据库对象:


Of course, when instanciating your classes, you'll have to specify the database object :

// somewhere, instanciate your DB class
$db = new Your_Db_Class();

// And, then, when instanciating your objects :
$obj = new MyClass1($db);


另一种方法是使用 Singleton设计模式 ,因此数据库类只能有一个实例.


Another way would be to use the Singleton design pattern, so there can be only one instance of your database class.

可能更容易设置;但是之后不太容易进行单元测试.

Probably a bit easier to setup ; but less easy to unit-test, after.

这篇关于了解PHP继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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