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

Php无法创建对象并访问其属性,php,Php,我创建了一个代表扑克游戏的游戏类。我试图从数据库中读取它并显示其中一个属性,例如NoOfPlayers,但我无法让它工作。这是课堂 class pokerGame { public $GameID, $State, $BuyIn, $Ante, $NoOfPlayers; function __construct() { $GameID = $BuyIn = $Players = $Ante = 0; $State = ""; } function withID($n

我创建了一个代表扑克游戏的游戏类。我试图从数据库中读取它并显示其中一个属性,例如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永远不会被设置。 改变

对这个

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

对所有的成员变量调用都这样做

实际的问题是什么?您得到的错误是什么?未捕获错误:在null上调用成员函数getNoOfPlayers()。基本上,对象为null。您的
read
函数不返回对象,它什么也不返回,为什么要用它的返回覆盖实际对象?只需将第二行更改为
$thisPokergame->withID(“3”)
您不应该在类方法中使用
global
。将连接传递给构造函数并将其作为类属性保留,然后将其引用为
$this->conn
 $this->NoOfPlayers = $row["NoOfPlayers"];