如果 $mysqli 对象声明在范围之外,如何在类中使用它


How can I use my $mysqli object inside my class if it's declared outside of scope?

我刚开始做OOP,所以如果有一个简单的解决方案,我提前道歉。基本上,我需要在中使用我的$mysqli对象。我已将其分成两个文件。

配置2.php

class Config
{
    public $host = 'localhost';
    public $username = '****';
    public $password = '****';
    public $database = '****';
    function report_error($query)
    {
        $email = '*@hotmail.com';
        $subject = 'MySQL error.';
        $message = "IP: {$_SERVER['REMOTE_ADDR']} 'n URL: http://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']} 'n'n MySQL query: {$query} 'n'n MySQL error: " . $mysqli->error();
        mail($email, $subject, $message);
        die('Oops, an error has occured. The administrator has been notified.');
    }
}
$config = new Config();
$mysqli = new mysqli($config->host, $config->username, $config->password, $config->database);
if($mysqli->connect_error)
    report_error($mysqli);

管理.php

require('includes/config2.php');
$mysqli->real_escape_string();   // Works out of scope.
class Account
{
    public $username = $mysqli->real_escape_string();   // Doesn't work in scope.
    public $password;
    function login()
    {
    }
}

感谢您的帮助,我很感激:)。

您应该将对象传递给 Account 的构造函数并将其另存为私有实例变量。

Account直接依赖于mysqli的实例,所以通过在构造函数中将其指定为必需参数来明确这一点并没有错。这是确保无论何时使用Account mysqli对象也存在的唯一方法。如果你从全局状态访问它(通过静态访问器或直接访问全局范围),你永远无法保证它确实存在。

你应该封装$mysqli对象并使其成为静态

通常,您会将数据库封装在某个称为"DBConnection"或类似类的类中。并且此实例应将实际$mysqli对象作为单例进行管理

在(非常)短:

class Config
{
    public $host = 'localhost';
    [...]
    public static  $connectionObj 
    public static getConnection(){
      if (!isset($this->connectionObj ){
        $connectionObj = new mysqli($this->host, $config->this, $config->this, $this->database);
        if($mysqli->connect_error){
          report_error($mysqli);
        }
      }
      return $this->connectionObj;
    }
}

您可以从任何位置访问此对象:

$mysqlObj = Config.getConnection()

免責聲明:这是非常短的,未经测试的代码和数据库不应该进入配置类,而是它自己的数据库类,所有SQL函数作为方法,这只是为了重用你提供的代码