我的numberOfDecks方法遇到问题。我尝试调用在我的构造函数中创建的卡片数组,但是一个错误不断出现,我传递了一个未定义的变量($ cards)。我认为因为它是一个全局变量,所以$ cards可以被调用到numberOfDecks方法。
<?php
/* creating a deck of cards class to be used in a blackJack game*/
class Deck{
public $cards = array();
//creates an instance of a deck of cards (works)
public function __construct(){
$values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A');
$suits =array('Diamond','Club','Heart','Spade');
foreach ($suits as $suit) {
foreach($values as $value){
$this->cards[] = "$value of $suit's";
}
}
}
/*trying to add more decks to increase number of total cards
in my array (does not work)*/
public function numberOfDecks($number){
$this->cards = $cards;
$this->number= $number;
for($i = 0 ; $i < $number; $i++){
array_push($cards[],$i);
}
return $cards;
}
}
$deck = new Deck();//works as expected
$deck->numberOfDecks(3);//trouble
$shuffled = shuffle($deck->cards);//works as expected
var_dump($deck);
答案 0 :(得分:1)
您的变量$cards
未定义,因为您没有声明它。
public function numberOfDecks($number){
$this->cards = $cards;
你可能想要翻转分配方向。
$cards = $this->cards;
鉴于您对在对象总牌中添加套牌的评论,在翻转分配方向后,请尝试使用array_merge
<?php
class Deck{
public $cards = array();
//creates an instance of a deck of cards (works)
public function __construct(){
$values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A');
$suits =array('Diamond','Club','Heart','Spade');
foreach ($suits as $suit) {
foreach($values as $value){
$this->cards[] = "$value of $suit's";
}
}
}
public function numberOfDecks($number){
$cards = $this->cards;
$this->number = $number;
for($i = 0 ; $i < $number; $i++){
$this->cards = array_merge($this->cards, $cards);
}
}
}
$deck = new Deck();//works as expected
// how many cards are intially constructed?
echo "count of cards in new deck: " . count($deck->cards) . "\n<br/>\n";
// add 3 more decks of cards
$deck->numberOfDecks(3);//trouble
echo "count of cards after adding 3 decks: " . count($deck->cards);
// $shuffled = shuffle($deck->cards);//works as expected
// var_dump($deck);
此输出结果:
新牌组中的牌数:52
添加3个套牌后的卡数:208