如何在PHP中使用array_shift()返回一个对象?

时间:2011-02-19 08:05:05

标签: php arrays object

我正在建立一些玩扑克牌的课程。我有一个Card类和一个Deck类。我想通过在Card对象数组上使用array_shift()来实现从卡片中绘制卡片;这个数组是Deck的一个属性。这是类的代码,它存储在文件“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;
 }

}

?>

这是测试代码,在“index.php”中:

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

?>

测试代码给出了以下错误消息:

NULL 致命错误:在第6行的C:\ wamp \ www \ cardgames \ index.php中的非对象上调用成员函数display()

似乎array_shift()没有返回对卡对象的引用,或者我没有使用array_shift()返回的内容正确初始化$ card变量。我如何获得我想要的对象?

2 个答案:

答案 0 :(得分:1)

在构造函数中,将堆栈存储在局部变量中。使用$this->stack将其存储在成员变量中。

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

答案 1 :(得分:1)

Deck::__construct()中,使用$this->stack[] = ..代替$stack[] = ..