具有Singleton的PDO无法访问私有财产 [英] PDO with Singleton cannot access private property
问题描述
我已经与PDO和单例模式建立了数据库连接.
只要将$_db
变量设置为public,一切都可以正常工作,但是它必须是私有的.当我将它设为私有时,我当然会得到错误:无法访问私有属性Database :: $ _ db
有人可以告诉我如何将其设为私有并仍然能够获得实例吗?
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?
当我从另一个文件调用数据库连接时,我调用函数getInstance()
这是我从一个文件中调用它的示例:
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);
}
}
推荐答案
您不需要写
You don't need to write
$ db-> _ db->
因为您已经在使用类的实例.
$db->_db->
Because you're already using instance of your class.
这里有您的数据库类的引用
Here you have a reference of your DB class
$db = Database::getInstance();
每次决定进行查询或填充时仅使用$db->query();, $db->prepare();
Every time when you decide to make a query or someting use only $db->query();, $db->prepare();
查看您的代码:您已经在$ DB类中使用$ _db引用. 因此,您无需将$ _db称为公共变量.
Look at your code: you're already using $_db reference in you DB class. So, you don't need to call $_db as public variable.
这篇关于具有Singleton的PDO无法访问私有财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!