【问题标题】:PHP Connection class using private and public [duplicate]使用私有和公共的PHP连接类[重复]
【发布时间】:2015-07-21 03:29:09
【问题描述】:

密码:

class mysql_db{
    private $conn;
    private function connect(){
        if(isset($this->$conn)){
            $this->$conn = new mysqli("localhost", "php_user", "php_pass", "db");
            if($this->$conn->connect_error)
                die("Connection failed: " . $this->$conn->connect_error);
        }
    }
    private function disconnect(){
        $this->$conn->close();
        unset($this->$conn);
    }

    public function getContent(){
        $this->connect();
        $stmt = $this->$conn->prepare("SELECT * FROM content");
        if($stmt->execute()){
            $stmt->bind_result($id, $type, $title, $text, $inserted);
            while($stmt->fetch()){
                printf("%s %s %s %s %s\n",$id, $type, $title, $text, $inserted);
            }
        }
        disconnect();
    }
}

$db = new mysql_db();
$db->getContent();

结果:

Notice: Undefined variable: conn in db.php on line 5
Notice: Undefined variable: conn in db.php on line 18
Fatal error: Cannot access empty property in db.php on line 18

问题:

为什么会发生这种情况,如何解决?

目标:

创建连接类,同时限制用户只能使用 PUBLIC 功能。将所有对数据库的访问保持在它自己的类中。

编辑: 解决方案:It was only $ mistake.

【问题讨论】:

  • $this->conn 去掉美元符号
  • ^ + disconnect(); $this-> 来调用类方法
  • 该死的,我错过了。都是关于$ lol的,我应该删除这个问题吗?
  • @Rizier123 这个问题怎么会重复?我确实检查了那个,它是不同的。

标签: php mysql oop access-modifiers


【解决方案1】:

您不应该使用 $ 符号两次。

$this->$conn =

应该是

$this->conn =

$ 表示引用一个变量,如果你已经引用了它,不需要它两次,它会报错。

也在第 18 行使用它。 $this->conn->prepare("SELECT * FROM content");

使用$this->disconnect();,因为它不是您的自定义函数。您需要断开当前对象,因此请使用 $this。

【讨论】:

    猜你喜欢
    • 2014-09-21
    • 2014-07-22
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 2019-08-26
    • 2013-08-09
    • 1970-01-01
    • 2015-12-11
    相关资源
    最近更新 更多