Jump to content

How to instantiate mysqli in class


Fmdpa

Recommended Posts

I am creating a User's class, and several methods require a database connection. Instead of instantiating mysqli in each method that needs it, how would I instantiate it for public access?I tried this:

class User {   __construct() {	  require_once 'db.php';	  public $db;  }//methods}

where db.php is:

define('HOST', 'localhost');define('USER','root');define('PASS','');define('DB','database');$db = new mysqli(HOST,USER,PASS,DB);

with no success. The error it gave me was caused by stating the scope of $db.

Link to comment
Share on other sites

It will be easiest if you add the connection as an argument to the constructor, but you could also create a static method that you call, and modify a static property from within it, like:

class Db {	private static connection;	public const HOST = 'localhost';	public const USER = 'root';	public const PASS = '';	public const DATABASE = 'database';	public static getInstance() {		if (is_object(self::$connection)) {			return self::$connection;		}else {			return self::$connection = new mysqli(self::HOST, self::USER, self::PASS, self::DATABASE);		}	}}class User {	protected db;	__construct() {		$this->db = Db::getInstance();	}	//methods}

Link to comment
Share on other sites

"Unexpected T_VARIABLE on Line 3" (private static connection;)When you define the scope of a property, must you preface it with the $ sign? Also, I'm having trouble understanding this:

if (is_object(self::$connection)) {	 return self::$connection;}

Is that checking if the $connection object is already instantiated? If so, we didn't get to the line that instantiates it, yet, so why would it be?

Link to comment
Share on other sites

Yes, all variables need to be prefixed with $. The condition is so that the first time Db::getInstance() is called, the MySQL-i instance is created. Then on future calls, the existing object is used (because, as a class variable, it already exists).

Link to comment
Share on other sites

Ok, I just assumed that the object was recreated each time the script ran. So I should make it like this:

class Db {	private static $connection; //change no. 1	public const HOST = 'localhost';	public const USER = 'root';	public const PASS = '';	public const DATABASE = 'database';	public static getInstance() {		if (is_object(self::$connection)) {			return self::$connection;		}else {			return self::$connection = new mysqli(self::HOST, self::USER, self::PASS, self::DATABASE);		}	}}class User {	protected $db; //change #2	__construct() {		$this->db = Db::getInstance();	}	//methods}

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...