0

我有这个类(它是简单的卡片类):

    class Card{
private $suit;
private $rank;

public function __construct($suit, $rank){
    $this->$suit = $suit;
    $this->$rank = $rank;
}

public function get_suit(){
    return $this->$suit;
}

public function get_rank(){
    return $this->$rank;
}
    }

我将每张卡片(带有花色和等级)作为套牌实例:

        $tmp_deck = array();
    foreach ($SUITS as $suit){
        foreach($RANKS as $rank){
            array_push( $tmp_deck, new Card($suit, $rank) );
        }
    }
    echo $tmp_deck[0]->get_suit();

它给了我错误:

Notice: Undefined variable: suit in card.php on line 13

我真的不明白出了什么问题。谁能帮我 ?

4

2 回答 2

3

类变量访问喜欢$this->suit不喜欢$this->$suit

改变这个

public function __construct($suit, $rank){
$this->$suit = $suit;
$this->$rank = $rank;
}

public function __construct($suit, $rank){
   $this->suit = $suit;
   $this->rank = $rank;
}

也改变其他人。

于 2013-02-22T11:39:05.797 回答
2

更改$this->$suit为,访问类变量时$this->suit不需要。$相同的$this->$rank->$this->rank

于 2013-02-22T11:38:59.357 回答