防止对象的多个实例

时间:2023-02-01 13:36:52

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?

我有一个超类,它实例化我的Sql类,所以所有派生类将能够执行查询,而无需在构造后实例化自己的Sql实例。这很好,但我有一个问题,我很困惑。其中一个派生类在其构造函数中实例化另一个派生类,所以现在,我相信我有两个Sql类实例打开,因为每个实例化父类。我无法覆盖任何派生类中的父类,因为它们都需要访问数据库实例才能执行自己的查询。当另一个派生类实例化它时,有没有办法阻止派生类调用父构造函数?

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?

您认为这种方法是否有意义,或者您是否预见到未来会出现的任何错误?

1 个解决方案

#1


3  

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:

我认为你要做的是使用单例模式。为此,您应该将构造函数声明为私有方法:

private function __construct() {

}

and initialize it once by calling a static method for example:

并通过调用静态方法初始化一次,例如:

static function connect_to_mysql() {
    //procedure of connecting...
}

myClass::connect_to_mysql();

#1


3  

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:

我认为你要做的是使用单例模式。为此,您应该将构造函数声明为私有方法:

private function __construct() {

}

and initialize it once by calling a static method for example:

并通过调用静态方法初始化一次,例如:

static function connect_to_mysql() {
    //procedure of connecting...
}

myClass::connect_to_mysql();