如何在函数内部使用DB类的实例?

时间:2014-06-24 13:23:38

标签: php

这是我的DB类。 (db.php中)

<?php

    class DB {
        protected $db_name = "data_db";
        protected $db_user = "root";
        protected $db_pass = "root";
        protected $db_host = "localhost";

        public function __construct() {
            $this->mysqli = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
        }

        public function __destruct() {
            $this->mysqli->close();
        }
    }

?>

这是我的users.php文件。

<?php

    require_once "core/DB.php";

        function user_data() {
            global $db;
            $db = new DB();
            $data = array();
            $session_user_id = $_SESSION["user_id"];
            $data_row = $db->mysqli->query("SELECT * FROM `users` WHERE `user_id` = '$session_user_id'");
            $data = $data_row->fetch_assoc();
            return $data;
    }
?>

如何在我的函数中使用DB类的$ db实例? 我应该只调用一次实例,而不是将其作为全局变量用于所有函数吗?

1 个答案:

答案 0 :(得分:2)

pleeeeaaase,不要使用全局变量

以单例模式尝试

class DB {
    protected $db_name = "data_db";
    protected $db_user = "root";
    protected $db_pass = "root";
    protected $db_host = "localhost";

    public static function getInstance()
    {
        static $instance = null;

        if (is_null($instance)) {
            $instance = new DB();
        }

        return $instance;
    }

    public function __construct() {
        $this->mysqli = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
    }

    public function __destruct() {
        $this->mysqli->close();
    }
}

在你的功能中你可以使用它而不是这种方式

function user_data() {
    $db = DB::getInstance();
    $data = array();
    $session_user_id = $_SESSION["user_id"];
    $data_row = $db->mysqli->query("SELECT * FROM `users` WHERE `user_id` = '$session_user_id'");
    $data = $data_row->fetch_assoc();
    return $data;
}

只需致电DB::getInstance()即可获得同一个班级实例