1

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.

11
  • What is the actual problem? What error are you getting? Commented Apr 13, 2016 at 23:26
  • Uncaught Error: Call to a member function getNoOfPlayers() on null. Commented Apr 13, 2016 at 23:27
  • Basically the object is null Commented Apr 13, 2016 at 23:28
  • Your read function 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"); Commented Apr 13, 2016 at 23:31
  • 1
    You should not be using global in a class method. Pass the connection to the constructor and keep it as a class property, then reference it as $this->conn Commented Apr 14, 2016 at 0:14

1 Answer 1

1

your not accessing member variables properly so your noOfPlayers is never being set. change

$NoOfPlayers = $row["NoOfPlayers"];

to this.

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

and do that for all of your member variable calls

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.