繁体   English   中英

如果在类之外声明了$ mysqli对象,该如何在类中使用它?

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

我刚刚开始做OOP,所以如果有一个简单的解决方案,我先向您道歉。 基本上,我需要使用一个里面我的$ mysqli的对象。 我将其分为两个文件。

config2.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);

Administration.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()

免责声明:这是很短的代码,未经测试的代码和数据库不应进入config类,而应使用所有SQL函数作为方法的自己的数据库类,这仅是为了重用您提供的代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM