rexhin
rexhin

Reputation: 449

How to use the instance of DB class inside functions?

This is my DB class. (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();
        }
    }

?>

This is my users.php file.

<?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;
    }
?>

How can I use the $db instance of DB class inside my functions? Should I call the instance only once and than make it a global variable to use in all functions?

Upvotes: 1

Views: 192

Answers (1)

bukart
bukart

Reputation: 4906

pleeeeaaase, don't use global variables

try it with a singleton pattern

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();
    }
}

in your functions you can use it than this way

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;
}

just call DB::getInstance() to get all time the same instance of your class

Upvotes: 2

Related Questions