我如何在类中使用子类?我尝试使用extends,但我认为这不是我想要的。
class Database
{
protected $link;
private $host, $database, $username, $password;
public function __construct($host, $database, $username, $password)
{
$this->host = $host;
$this->database = $database;
$this->username = $username;
$this->password = $password;
$this->connect();
}
private function connect()
{
$this->link = new mysqli($this->host, $this->username, $this->password, $this->database);
//GLOBAL $this->link
if ($this->link->connect_errno)
die('Connection Error: ' . $this->link->connect_errno);
}
public function __sleep()
{
return array('host', 'database', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
}
class Users extends Database{
public function getAll(){
$stmt = Database->link->prepare('SELECT id, username, email FROM USERS');
$stmt->execute();
$stmt->bind_result($id, $username, $email);
while($stmt->fetch())
$row[] = array('id' => $id, 'username' => $username, 'email' => $email);
$stmt->close();
return $row;
}
}
然后在显示内容的文件中......
$db = new Database(HOST, DATABASE, USER, PASSWORD);
$users = $db->Users->getAll();
foreach($users as $user){
echo $user['username'] . "<br />";
}
我认为我的问题在于$stmt = Database->link->prepare
和$users = $db->Users->getAll();
我更像是一个C家伙,所以PHP方法有点让我。有人可以准确地描述我需要做什么才能获得正确的子类化方法吗?
答案 0 :(得分:2)
我认为我的问题在于
$stmt = Database->link->prepare
和$users = $db->Users->getAll()
你做对了。
当Users
扩展Database
时,它可以访问受保护的属性$link
,因此,您只需通过$this
使用它,例如
$stmt = $this->link->prepare(...)
现在,每次实例化Database
类或其后代时,您都不希望创建新的MySQL连接。相反,您应该将mysqli
依赖项传递给构造函数,例如
abstract class Database {
protected $link;
public function __construct(mysqli $link) {
$this->link = $link;
}
}
class Users extends Database {
public function getAll() {
$stmt = $this->link->prepare(...);
// and so on
}
}
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$usersDao = new Users($mysqli);
$users = $usersDao->getAll();
foreach($users as $user){
echo $user['username'] . "<br />";
}