Php 在类方法中打开数据库连接

Php 在类方法中打开数据库连接,php,Php,要打开DB连接,我当前使用以下类方法: function openDB() { // 1. Create a database connection $conn = mysqli_connect("x" , "x", "x","x"); if (!$conn) { $this->error_msg = "connection error could not connect to the database:! "; return false; } $this-

要打开DB连接,我当前使用以下类方法:

    function openDB() {


// 1. Create a database connection
$conn = mysqli_connect("x" , "x", "x","x");
if (!$conn)
{
    $this->error_msg = "connection error could not connect to the database:! ";  
    return false;
}
$this->conn = $conn;
return true;
}
但是,我想改用我的配置文件

require("assets/configs/db_config.php");
显然,该文件包含数据库连接信息

我怎样才能摆脱这种状态呢

$conn = mysqli_connect("x" , "x", "x","x");
只需创建$conn并使用DB_Config.php即可?

更改

function openDB()

并将这些变量传递给mysqli_connect

并从包含的文件中传递数据。我想,它们在某种常量或定义中


另外,最好在全局某个地方建立数据库连接。

对于您的配置文件,它将返回您需要的值数组

 return array("host"=>"example.com", "dbname"=>"mydb", "username"=>"dbuser", "password"=>"secret");
然后在openDb函数中执行此操作

function openDB() {
  // 1. Create a database connection
  $config = include("/path/to/config.php");
  $conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
  if (!$conn)
  {
    $this->error_msg = "connection error could not connect to the database:! ";  
    return false;
  }
  $this->conn = $conn;
  return true;
}
是的,我会:
那么我在函数中会做什么呢$conn还需要定义连接吗?
function openDB() {
  // 1. Create a database connection
  $config = include("/path/to/config.php");
  $conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
  if (!$conn)
  {
    $this->error_msg = "connection error could not connect to the database:! ";  
    return false;
  }
  $this->conn = $conn;
  return true;
}