将mysql转换为mysqli-如何获取超全局连接对象? [英] Converting mysql to mysqli - how to get superglobal connection object?

查看:60
本文介绍了将mysql转换为mysqli-如何获取超全局连接对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将代码从mysql转换为mysqli. 该代码在文件中使用了一个mysql_connect,其他所有文件都包含该文件.

I am trying to convert code from mysql to mysqli. The code uses a single mysql_connect in a file which is included by every other file.

mysql_connect返回一个超链接的MySQL链接标识符,因此您可以依靠自己的任何函数中的可用数据库连接.

mysql_connect returns a MySQL link identifier that is a superglobal so you can rely on having a database connection available in any of your own functions.

看起来不是mysqli_connect,返回的对象不是全局的.

It looks like with mysqli_connect this is not the case, the object returned isn't global.

这是否意味着我必须添加:global $ mysqli;在每个函数的顶部,还是有办法使其成为超全局变量?

Does this mean I have to add : global $mysqli; at the top of every function, or is there an way of making it a superglobal?

推荐答案

如果您不指定PHP,那么依靠PHP将使用最后打开的连接资源这一事实可能不是一个好主意.
如果您的应用程序发生更改并且需要两个连接,或者连接不存在,该怎么办?
因此,看来您仍然需要进行一些重构.

Relying on the fact that PHP will use the last opened connection resource if you don't specify one, is probably not a very good idea.
What happens if your application changes and you need two connections, or the connection is not there?
So it seems you need to do some refactoring anyway.

这是一种类似于Karsten的解决方案,总是返回相同的mysqli对象.

Here's a solution similar to Karsten's that always returns the same mysqli object.

class DB {
    private static $mysqli;
    private function __construct(){} //no instantiation

    static function cxn() {
        if( !self::$mysqli ) {
            self::$mysqli = new mysqli(...);
        }
        return self::$mysqli;
    }
}        

//use
DB::cxn()->prepare(....

这篇关于将mysql转换为mysqli-如何获取超全局连接对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆