1

I'm building some classes for working with playing cards. I have a Card class and a Deck class. I want to implement drawing a card from the deck by using array_shift() on an array of Card objects; this array is a property of Deck. Here is the code for the classes, which is stored in the file "cardlib.php":

<?php
class Card
{
 private $suit="";
 private $face="";

 function __construct($suit,$face){
    $this->suit=$suit;
    $this->face=$face;
 }

 public function getSuit(){
    return $suit;
 }

 public function getFace(){
    return $face;
 }

 public function display(){
    echo $this->suit.$this->face;
 }

}


class Deck
{
 private $suits=array("S","H","C","D");
 private $faces=array("2","3","4","5",
            "6","7","8","9","10",
            "J","Q","K","A");
 private $stack=array();

 function __construct(){
    foreach ($this->suits as $suit){
        foreach ($this->faces as $face){
            $card = new Card($suit,$face);
            $stack[] = $card;
        }
    }

 }

 public function doShuffle(){
    shuffle($this->stack);
 }

 public function draw(){
    $card = array_shift($this->stack);
    var_dump($card);
    return $card;
 }

}

?>

And here is the test code, in "index.php":

<?php
include_once "cardlib.php";
$myDeck=new Deck();
$myDeck->doshuffle();
$card=$myDeck->draw();
$card->display();

?>

The test code gives me the following error message:

NULL Fatal error: Call to a member function display() on a non-object in C:\wamp\www\cardgames\index.php on line 6

It seems that array_shift() isn't returning the reference to the card object, or I'm not properly initializing the $card variable with what array_shift() returns. How do I get the object that I want?

2 Answers 2

1

In the constructor, you store the stack in a local variable. Use $this->stack to store it in the member variable.

function __construct(){
   foreach ($this->suits as $suit){
       foreach ($this->faces as $face){
           $card = new Card($suit,$face);
           $this->stack[] = $card;
       }
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

In Deck::__construct(), use $this->stack[] = .. instead of $stack[] = ..

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.