开发者

How do I return an object with array_shift() in PHP?

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?


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;
       }
   }
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜