我无法接收我推入卡阵列的值。我不知道是不是我没有调用正确的属性,或者我只是没有正确添加到数组中。
<?php
class Deck{
public function __construct(){
$values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A');
$suits =array('Diamond','Club','Heart','Spade');
$cards = array();
foreach ($suits as $suit) {
foreach($values as $value){
$cards[] = "$value of $suit's";
}
}
}
}
$deck = new Deck();
var_dump($deck);
答案 0 :(得分:3)
$cards
是__construct
的本地变量:一旦该函数结束,该变量就会蒸发。相反,您可能希望cards
成为该类的成员:
class Deck {
public $cards = [];
public function __construct() {
$values =array('2','3','4','5','6','7','8','9','10','J','Q','K','A');
$suits =array('Diamond','Club','Heart','Spade');
$cards = array();
foreach ($suits as $suit) {
foreach($values as $value){
$this->cards[] = "$value of $suit's";
}
}
}
}
然后,您可以在对象内使用$this->cards
,或在外部使用$deck->cards
。