MySQL connection: globally or in object?

后端 未结 4 1341
逝去的感伤
逝去的感伤 2021-01-18 07:23

I have two PHP classes. One is for connecting to the database, building queries, executing them, and disconnecting from the database. The other class is for users: adding th

4条回答
  •  清歌不尽
    2021-01-18 07:51

    Create a function that creates the connection on demand and provides access to the connection object:

    function getDb()
    {
        static $db;
        if (!$db) $db = ...;
        return $db;
    }
    

    Wrapped into class this approach is called Singleton

提交回复
热议问题