2013-02-22 107 views
0

我有這個類(這是簡單的卡類):PHP變量未定義錯誤

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 

我真的不能得到什麼是錯的。誰能幫我 ?

+1

$ this-> suit = $ suit; $ this-> rank = $ rank; – 2013-02-22 11:38:53

回答

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; 
} 

更改其他人。

+1

哇,我不會注意到在上百萬年。我不太熟悉PHP語法。謝謝! – carobnodrvo 2013-02-22 11:49:35

+0

@carobnodrvo接受答案是好習慣。如果它解決了你的問題:) – 2013-02-22 11:58:40

+1

你在同一分鐘內回答我無法馬上接受:) – carobnodrvo 2013-02-22 12:12:51

2

更改$this->$suit$this->suit,訪問類變量時不需要$。同爲$this->$rank - >$this->rank