如何在php类中引用数据库

时间:2013-03-11 21:39:07

标签: php mysql class

$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命令中使用该数据库连接。如何在我的课程中获得使用该数据库连接的能力?

6 个答案:

答案 0 :(得分:1)

你的$ mysqli只是超出了范围。你必须选择:

1)使用全局变量。

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

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

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

然后使用$this->_mysqli

从您的班级中引用它

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

class ACL {
    function DoSomething() {
        global $mysqli;
        ...
    }
}

答案 3 :(得分: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
       }
}

答案 4 :(得分:0)

你可以将你的mysqli包装在如下的类中:

class database {
    // do database stuff here
}

并扩展ACL

class ACL extends database {
    // do acl stuff here with all your database stuff available
}

答案 5 :(得分: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()
    }
}