I have a superclass which instantiates my Sql class so all derived classes will be able to perform queries without instantiating their own Sql instances once they are constructed.
This works good but I have a question I’m confusing myself about. One of the derived classes instantiates another derived class in its constructor so now, I believe I have 2 instances of the Sql class open because each instantiates the parent. I cannot override the parent class in any of the derived classes because they all need access to a a database instance to perform their own queries. Is there a way to prevent the derived class from calling the parent constructor when another derived class instantiates it?
I’m thinking passing a parameter to the class and only calling the parent constructor if meets the requirements as such.
function__construct($param) {
if($param == false) {
parent::__construct();
}
}
Do you think this approach makes sense, or do you forsee any bugs arising in the future?
I think what you’re trying to do is using the singleton pattern. To do that, you should just declare your constructor as a private method:
and initialize it once by calling a static method for example: