【发布时间】: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