Right, basically I've got an MySQLi singleton wrapper which I want to use in other classes.
It is as follows:
So, rather than doing
...and opening a new connection to the database each time, I do
...which will check if a connection has already been established and just return it. Easier on the database
Now, I want to use this in other classes, for example:
...but this does not allow me to to use my getInstance() method, how would I go about being able to do this?
Thanks,
Mark
It is as follows:
PHP:
<?php
class Database extends PDO {
public static $instance;
private $connection;
public function __construct() {
$this->connection = parent::__construct('mysql:host=localhost;dbname=lol', 'lol', 'lol');
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
So, rather than doing
PHP:
$query = $db->prepare("SELECT......");
PHP:
$query = $db::getInstance()->prepare("SELECT.......");
Now, I want to use this in other classes, for example:
PHP:
<?php
class Core {
private $_db;
public function __construct(Database $db) {
if (!$db || $db->connect_errno > 0) {
die ('MySQLi connection error. Error sent from class.core.php');
} else {
$this->_db = $db;
}
}
public function AddLog($User, $Event) {
$log = $this->_db->prepare("INSERT INTO `Logs` (`UserID`, `Event`, `TimeStamp`, `IPAddress`) VALUES (?, ?, ?, ?);");
if ($log->execute([$User, $Event, time(), $_SERVER['REMOTE_ADDR']])) {
return true;
}
return false;
}
}
...but this does not allow me to to use my getInstance() method, how would I go about being able to do this?
Thanks,
Mark