我正在建立一些與撲克牌一起工作的課程。我有一個卡類和一個Deck類。我想通過在Card對象數組上使用array_shift()來實現從卡組中繪製卡片;這個數組是Deck的一個屬性。下面是類,這是存儲在文件「cardlib.php」代碼:如何在PHP中使用array_shift()返回對象?
<?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 致命錯誤:調用一個成員功能顯示()在C語言的非對象:\瓦帕\ WWW \ cardgames \的index.php第6行
看起來,似乎如果array_shift()沒有返回對卡對象的引用,或者我沒有正確初始化array_shift()返回的$ card變量。我如何獲得我想要的對象?