我有一个扩展另一个类的PHP类,但我只让MySQL在扩展类中工作而不是第一个类。谁知道问题可能是什么?我现在似乎无法弄明白:S
# Vote class.
class vote {
public $newsID;
private $db;
# Construct.
public function __construct() {
global $_database;
$this->db = $_database;
}
# Vote Up.
public function voteUp() {
return '<a href="#" class="fa fa-angle-up" style="position:absolute;top: 1px; right: 10px;"></a>';
}
public function voteScore($newsID) {
$vote = mysqli_fetch_object($this->db->query("SELECT * FROM ".PREFIX."news WHERE newsID='".$newsID."' LIMIT 1"))->vote;
return '<span class="BigFontSize" style="position:absolute; top: 37px;right: 14px;">'.$vote.'</span>';
}
public function voteDown() {
return '<a href="#" class="fa fa-angle-down" style="position:absolute; bottom: 0;right: 10px;"></a>';
}
}
# News class.
class news extends vote {
public $countNews;
private $db;
# Construct.
public function __construct() {
global $_database;
$this->db = $_database;
}
# Count News.
public function countNews() {
return $this->db->query("SELECT * FROM ".PREFIX."news ORDER BY date DESC")->num_rows;
}
# Print the news.
public function GetNews() {
$newsArray = array();
$sql = $this->db->query("SELECT * FROM ".PREFIX."news ORDER BY date DESC");
while ($rad = $sql->fetch_array()) {
$newsArray[] = array('headline' => $rad['headline'], 'content' => $rad['content'], 'date' => $rad['date'], 'poster' => $rad['userID'], 'published' => $rad['published'], 'intern' => $rad['intern'], 'newsID' => $rad['newsID']);
}
return $newsArray;
}
}
投票类没有正常运行的数据库。我错过了什么吗?
答案 0 :(得分:1)
只需从新闻中删除构造函数,它就会继承投票构造函数。您必须使$ db class var保持投票而不是私有,并将其从新闻中删除。每个人都拥有自己对同一个$ database的引用,绝对没有收获,因为它仍然是同一个实例。
虽然我们讨论的是更好的代码设计,但不要在PHP中使用GLOBAL。 PHP global in functions http://smartik.ws/2014/07/do-not-use-php-global-variables-never/
不使用构造函数中的全局连接对象,而是使用依赖注入,即将其作为参数传递给构造函数:
android:background="@null"
从长远来看,你会发现这是首选的做法,原因非常充分。它也将标记为专业人士而非业余爱好者。 http://tutorials.jenkov.com/dependency-injection/index.html