PHP 连接 class 使用私有和 public

PHP Connection class using private and public

代码:

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

问题:

Why this happen, and how to fix it?

目标:

Creating a connection class while limiting it user to use only PUBLIC function. Keeping all access to database inside it own class.

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

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

$this->$conn =

应该是

$this->conn =

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

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

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