0

简单的数据访问层程序。我有一个类,其中包含一些用于用户名密码等的受保护变量。我有一个读取 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 一起!

谢谢

4

2 回答 2

0

这是我想出的一种方法......我不知道这是好还是正确!:)

补充:

public function connect()
{
    return $this->conn = mysqli_connect($this->server, $this->user, $this->pwd, $this->db); 
}

function fetchMyStucc
{
    $query = mysqli_query($this->connect(), $query, ...)

似乎工作。

感谢您的建议!它有帮助

于 2013-09-28T18:23:19.643 回答
0

我认为您的__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;

于 2013-09-28T18:09:15.917 回答