Friday, 15 January 2010

php - How to use the instance of DB class inside functions? -



php - How to use the instance of DB class inside functions? -

this 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 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 * `users` `user_id` = '$session_user_id'"); $data = $data_row->fetch_assoc(); homecoming $data; } ?>

how can utilize $db instance of db class within functions? should phone call instance 1 time , create global variable utilize in functions?

pleeeeaaase, don't utilize global variables

try 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(); } homecoming $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 functions can utilize way

function user_data() { $db = db::getinstance(); $data = array(); $session_user_id = $_session["user_id"]; $data_row = $db->mysqli->query("select * `users` `user_id` = '$session_user_id'"); $data = $data_row->fetch_assoc(); homecoming $data; }

just phone call db::getinstance() time same instance of class

php

No comments:

Post a Comment