简单的数据访问层程序。我有一个类,其中包含一些受保护的用户名密码等变量。我有一个函数可以读取 INI 文件并填充那些受保护的变量。喜欢这个
class SqlAdapter
{
protected $_connection
protected $_username
protected $_passwprd
protected $_hostname
public function __construct()
{
$params = parse_ini_file(__file__, 1);
$this->_username = $params[...][...];
...
...
[where the problem comes in]
$this->_connection = mysqli_connect($this_hostname, ..., ...);
}
public function fectchMyStuff()
{
$result array()
$query = mysqli_query($connection, $query, MYSQLI_STORE_RESULT);
while($row = mysqli_fetch_assoc($query))
{
$result[] = $row;
}
return json_encode($result);
}
现在,当我在函数中运行连接内容时,它工作得很好......但是为什么受保护的变量在构造函数实例化后没有"保持电荷"呢?我做错了什么吗?
有什么建议吗?关键是,我不想每次编写访问数据库的函数时都必须重写该连接字符串......有点违背了可重用代码和封装的目的,好吧,OOP 一起!
谢谢
我认为您的__construct
函数还可以,但是fectchMyStuff
似乎有些不对劲:
public function fectchMyStuff()
{
$result array()
// $query = mysqli_query($connection, $query, MYSQLI_STORE_RESULT);
// should use $this->_connection
$query = mysqli_query($this->_connection, $query, MYSQLI_STORE_RESULT);
while($row = mysqli_fetch_assoc($query))
{
$result[] = $row;
}
return json_encode($result);
}
更新
$this->_connection = mysqli_connect($this_hostname, ..., ...);
$this_hostname
,你是说$this->_hostname
吗?
这是我想出的一种方法...我不知道这是好还是对!:)
附加契约:
public function connect()
{
return $this->conn = mysqli_connect($this->server, $this->user, $this->pwd, $this->db);
}
function fetchMyStucc
{
$query = mysqli_query($this->connect(), $query, ...)
似乎有效。
感谢您的建议! 它有帮助