I have created a game class which represents a poker game. Im trying to read it in from a db and display one of the attribute e.g NoOfPlayers but i cannot get it working. Here is the class.
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;
}
}
and here is how im trying to access it.
$thisPokergame = new pokerGame();
$thisPokergame = $thisPokergame->withID("3");
echo $thisPokergame->getNoOfPlayers();
Pretty sure my error is in the class as my object is NULL, i tried viewing the attributes using the get_object_vars method.
readfunction doesn't return an object, it returns nothing at all, why would you overwrite your actual object with the return of it? Just change your second line to$thisPokergame->withID("3");globalin a class method. Pass the connection to the constructor and keep it as a class property, then reference it as$this->conn