0

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?

2
  • Your question(s) is/are a bit ambiguous. Do you want a master single instance (singleton pattern), or a way to track new instances (factory pattern)? Commented Apr 26, 2011 at 22:00
  • Nowadays, PHP passes all instances of classes by reference. Commented Apr 26, 2011 at 22:03

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have thought of this way, but wondered if I could instantiate MyClass2 without having to pass the DB class to it and it just know of it because of the core class
No, there is no magic : even if the code is in the parent class, you still have to indicate the object (which uses code from both parent and child classes) on which db object it must work.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.