我创建了一个代表扑克游戏的游戏类。我试图从数据库中读取它并显示其中一个属性,例如NoOfPlayers但我无法使其工作。这是班级。
class pokerGame {
public $GameID, $State, $BuyIn, $Ante, $NoOfPlayers;
function __construct() {
$GameID = $BuyIn = $Players = $Ante = 0;
$State = "";
}
function withID($newGameID) {
$this->read($newGameID);
}
function read($newGameID)
{
global $conn;
$query = "SELECT * FROM games WHERE GameID = ".$newGameID." LIMIT 1";
$result = $conn->query($query) or die('Error getting values: '.$query);
$response = array();
if ($result->num_rows == 0) { return;}
$row = $result->fetch_assoc();
$GameID = $row["GameID"];
$State = $row["State"];
$BuyIn = $row["BuyIn"];
$Ante = $row["Ante"];
$NoOfPlayers = $row["NoOfPlayers"];
}
function write($buyIn,$ante)
{
global $conn;
$query = "INSERT INTO games (BuyIn,Ante) VALUES ('$buyIn','$ante')";
$conn->query($query) or die('Error Inserting Values: '.$query);
}
function getNoOfPlayers() {
return $this->NoOfPlayers;
}
}
以下是我试图访问它的方式。
$thisPokergame = new pokerGame();
$thisPokergame = $thisPokergame->withID("3");
echo $thisPokergame->getNoOfPlayers();
非常确定我的错误是在类中,因为我的对象是NULL,我尝试使用get_object_vars方法查看属性。
答案 0 :(得分:1)
您没有正确访问成员变量,因此永远不会设置您的noOfPlayers。 变化
$NoOfPlayers = $row["NoOfPlayers"];
到此。
$this->NoOfPlayers = $row["NoOfPlayers"];
并为所有成员变量调用执行此操作