使用global for mysqli_insert_id()

时间:2016-03-04 13:08:13

标签: php mysqli

我已经从PHP中的mysql函数迁移到mysqli函数(从PHP 5.4到PHP 5.5)。问题是大多数转换要求我使用全局,因为我有这样的功能:

function insert_custom_data($params, $table_name){
    global $conn;
  // do the mysql insert
  $id = mysqli_insert_id($conn);
  // ... rest of the code
}

是否有可能在不使用函数中的全局或参数的情况下使其工作?也许是上课?

1 个答案:

答案 0 :(得分:1)

class MySQLiConnection { 
      private static $conn = null;
      private function __construct() { }

      public static function getConnection() {
            if (static::$conn === null) { 
                static::$conn = mysqli_connect(/* your params go here */);
            }
            return static::$conn;
      } 
}

然后,您可以将所有global $conn替换为$conn = MySQLiConnection::getConnection()