0
$DB_HOST = "localhost";
$DB_NAME = "rawr";
$DB_USER = "rawr";
$DB_PASS = "hunter2!";
$tableprefix = "hunter_";
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
    class ACL
{....

我目前有,但我无法在我的所有 ACL 命令中使用该数据库连接。我怎样才能获得在课堂上使用该数据库连接的能力?

4

6 回答 6

1

您的 $mysqli 超出范围。你必须选择:

1)使用全局变量。

function XXXX () {
    global $mysqli;
    ...
}

2)将其传递给构造函数(这样更好)

public function __construct($mysqli) {
    $this->_mysqli = $mysqli;
}

然后在你的课堂上引用它$this->_mysqli

于 2013-03-11T21:44:55.790 回答
0

当您实例化它时,您需要将该 mysqli 实例传递给您的 ACL 类。它不会自动知道在类声明之外声明的局部变量。

于 2013-03-11T21:42:52.870 回答
0

确保您使用的连接处于正确的环境中。你可以这样做,例如global

class ACL {
    function DoSomething() {
        global $mysqli;
        ...
    }
}
于 2013-03-11T21:45:24.910 回答
0
 class ACL {

       public function __construct() {
            $DB_HOST = "localhost";
            $DB_NAME = "rawr";
            $DB_USER = "rawr";
            $DB_PASS = "hunter2!";
            $tableprefix = "hunter_";
            $conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
            if (mysqli_connect_errno()) {
                   printf("Connect failed: %s\n", mysqli_connect_error());
                   exit();
            } else {       
                   $this->conn = $conn;
            }
       }

       public function command1()
       {
            //use connection object as $this->conn 
            ///your code
       }
}
于 2013-03-11T21:47:53.583 回答
0

您可以将 mysqli 包装在一个类中,例如:

class database {
    // do database stuff here
}

并扩展 ACL

class ACL extends database {
    // do acl stuff here with all your database stuff available
}
于 2013-03-11T21:49:17.203 回答
0

这是另一种方法。将您的数据库连接抽象为一个单独的实用程序类:

<?php
class DB
{
    const DB_HOST = "localhost";
    const DB_NAME = "rawr";
    const DB_USER = "rawr";
    const DB_PASS = "hunter2!";

    protected static $instance;
    public static function instance()
    {
        if (empty(self::$instance))
        {
            self::$instance = new mysqli(self::DB_HOST, self::DB_USER, self::DB_PASS, self::DB_NAME);
        }

        return self::$instance;
    }
}

这不是控制反转,但数据库访问对于大多数应用程序来说非常重要,因此它可以非常安全地用作一种模式。

<?php

// Note: make sure DB class is loaded!

class ACL // Note: this doesn't extend DB!
{
    public function __construct()
    {
        // you can now access your $mysqli object with DB::instance()
    }
}
于 2013-03-11T23:07:20.503 回答