2013-02-22 111 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