Php无法创建对象并访问其属性


Php trouble creating object and accessing its attributes

我创建了一个代表扑克游戏的游戏类。我试图从数据库中读取它并显示其中一个属性,例如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方法查看属性。

您没有正确访问成员变量,因此您的noOfPlayers永远不会被设置。更改

$NoOfPlayers = $row["NoOfPlayers"];

对此。

 $this->NoOfPlayers = $row["NoOfPlayers"];

并对所有成员变量调用

执行此操作