我是oop php的新手,并从某处复制了源代码,修改并测试它们。不知道新用户类有什么问题。
class DB {
private $dbHost = "127.0.0.1";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "hihi";
public function __construct(){
if(!isset($this->db)){
// Connect to the database
try{
$conn = new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName.";charset=utf8", $this->dbUsername, $this->dbPassword);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = $conn;
} catch(PDOException $e){
die("Failed to connect with MySQL: " . $e->getMessage());
}
}
}
public function __destruct(){
$this->db = null;
}
public function display($sql){
..............
return html_table;
}
public function insert($sql){
..............
}
}
index.php //它不起作用
include 'DB.php';
include 'User.php';
$users = new User();
$users -> getAllUsers();
User.php //它不起作用
class User extends DB{
public function getAllUsers(){
$sql = "SELECT * FROM userview WHERE event = 'a' ORDER BY created DESC";
$users = $this->db->display($sql);
echo $users;
}
}
致命错误:在C:\ Program Files(x86)中调用未定义的方法PDO :: display()......
如果我将User.php更改为以下,
User.php //它不起作用
class User extends DB{
public function getAllUsers(){
$sql = "SELECT * FROM userview WHERE event = 'a' ORDER BY created DESC";
$users = $this->display($sql);
echo $users;
}
}
致命错误:用户对象([dbHost:DB:private] => 127.0.0.1 [dbUsername:DB:private] => root [dbPassword:DB:private] => [dbName:DB:private] => hihi [db] => PDO Object())
User.php //它不起作用
class User extends DB{
public function getAllUsers(){
$sql = "SELECT * FROM userview WHERE event = 'a' ORDER BY created DESC";
$users = display($sql);
echo $users;
}
}
致命错误:在C:\ Program Files(x86)中调用未定义的函数display()......
如果我不创建用户类,它就可以工作。
index.php //它有效
include 'DB.php';
$db = new DB();
$users = $db->display("SELECT * FROM userview WHERE event = 'a' ORDER BY created DESC");
echo $users;
我想创建类User,Company,....以扩展DB以便使用DB的类方法进行选择,更新,删除......但是会发生致命错误。 PLS。救命。非常感谢。