I´ve made a database connection with PDO and the singleton pattern.
Everything works fine as long as I have the $_db
variable set as public but it needs to be private... When I make it private I off course get the Error: Cannot access private property Database::$_db
Can someone tell me how to make it private and still be able to get an instance?
When I call the database connection from another file I call the function getInstance()
Here is an example how I call it from one file:
$db = Database::getInstance();
$query = $db->_db->prepare("SELECT `password`, `id` FROM `users` WHERE `username` = ?");
This is what my database connection file looks like:
class Database
{
private $_db;
static $_instance;
private function __construct()
{
$this->_db = new PDO('mysql:host=localhost;dbname=mvcuser', 'root', '');
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
private function __clone(){}
public static function getInstance()
{
if (!(self::$_instance instanceof self))
{
self::$_instance = new self();
}
return self::$_instance;
}
public function query($sql)
{
return $this->_db->query($sql);
}
}