Understanding PHP Inheritance

2019-09-14 03:06发布

问题:

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 {
    ....
}

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.

How should / can I go about this?

回答1:

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;
    }

}

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);


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.



回答2:

You could pass the database object as a parameter to the __construct function of your class, and then in said function assign the db object to member of the class, for instance $this->database_handler.

Another possibility is to work with a global variable that is your database object, but global variables are evil for many reasons, so let's disregard that.

Another note: By default, all objects are passed by reference, so you don't need to worry about that.