简体   繁体   English

PHP OOP扩展类无法访问数据库连接

[英]PHP OOP extending class can't access database connection

Perhaps you can help. 也许你可以帮忙。 I have a main class that creates a MySql connection. 我有一个创建MySql连接的主类。 Then I extend this class. 然后,我扩展了这一堂课。 I wasn't able to access the connection unless I did a parent::__construct(); 除非执行了parent :: __ construct();否则我无法访问该连接。 and recently while doing this I got an error message that I was out of connections. 最近在执行此操作时收到一条错误消息,提示我连接断开。

So how do program this so it doesn't run out of connections and can access the database connection. 因此,如何对此进行编程,以确保它不会耗尽连接并且可以访问数据库连接。

class Common 
{
    var $mysql;

    function __construct()
    {   
        $this->mysql=new mysqli($this->dbHOST, $this->dbUSERNAME, $this->dbPASSWORD, $this->dbNAME);
    }
}

class Role extends Common {

    function __construct()
    {
        parent::__construct();
    }
}

Make sure you close the connection when the object is destroyed. 确保销毁对象时关闭连接。 That is, add a __destruct() method that closes the connection. 也就是说,添加一个__destruct()方法来关闭连接。

If the Common class is the one that opens the connection in its __construct() method, then it should be the one to close it in its __destruct() method. 如果Common类是在其__construct()方法中打开连接的类,则它应该是在其__destruct()方法中关闭连接的类。 If you don't define a __destruct() method on the Role class, then it looks like PHP won't call the parent's __destruct() automatically. 如果未在Role类上定义__destruct()方法,则PHP似乎不会自动调用父级的__destruct() (I haven't tested this, though.) A simple solution is to add a stub __destruct() method that just calls parent::__destruct() . (不过,我尚未对此进行测试。)一个简单的解决方案是添加一个仅调用parent::__destruct()的存根__destruct()方法。

I think there is a fundamental problem with your class structure: You don't need a connection per object, you only need a copy of the connection resource per object. 我认为您的类结构存在一个根本问题:您不需要每个对象的连接,只需要每个对象的连接资源的副本。

My preferred way out of this is to create a database handler that has a singleton call. 我的首选解决方法是创建一个具有单例调用的数据库处理程序。 Now it can be called anywhere and it will always return the same connection handler. 现在可以在任何地方调用它,并且它将始终返回相同的连接处理程序。 This is also an excellent way to hide automatic initialization. 这也是隐藏自动初始化的绝佳方法。

The solution was borne out of the realization that a class representing a database row is actually quite different from a class that is a database connection. 该解决方案被证实了实现, 代表数据库中的一行一类实际上是从一类就是一个数据库连接完全不同的。 An app will deal with many many rows but rarely, if ever, will deal with more than one connection. 一个应用程序可以处理许多行,但很少(如果有的话)将处理多个连接。 Another way of putting this is the difference between the IS-A and HAS-A definitions: it doesn't make sense to say "a database row class IS-A database connection". 另一种表达方式是IS-A和HAS-A定义之间的区别:说“数据库行类IS-A数据库连接”没有任何意义。 It does make sense to say "a datbase row class HAS-A database connection". 说“一个datbase行类HAS-A数据库连接”确实很有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM