2013-12-09 57 views
0

爲什麼實例仍在處理卡?即使很清楚,$ isDealer標記默認爲false,除了經銷商?真/假....仍然處理卡?

$cards = array('Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King'); 
$suits = array('Hearts','Diamonds','Spades','Clubs'); 

class Person { 
public $isDealer = false; 
public $luck = 15; 

public function dealCards() { 
    if ($isDealer) { 

     global $cards; 
     global $suits; 

     for ($i = 0; $i < 5; $i++) { 
      $pulledcard = rand(0,count($cards)-1); 
      $pulledsuit = rand(0,count($suits)-1); 
      echo $dealt = $cards[$pulledcard] .' of '. $suits[$pulledsuit] . '<br>'; 
     } 
    } 
    else { 
     return 'You\'re not a dealer'; 
     } 
    } 
} 

class Baller extends Person { public $luck = 50; } 
class Dealer extends Person { public $isDealer = true; } 

$dealer = new Dealer(); 
$theman = new Baller(); 
$random = new Person(); 

echo $theman->dealCards();  //this should return you're not a dealer but it deals cards instead 

最後一部分應該返回一個「你不是經銷商!」而是交易卡。實際的「經銷商」也是如此。

+1

這不是做這件事的方法。 'dealCards()'應該在Dealer類中。 –

+0

你爲什麼使用'global'?這是一個非常糟糕的主意。 – Mike

+0

來吧傢伙,isDealer是顯然不是一個類,它的定義和使用程序 –

回答

5

你想

if ($this->isDealer) { 
+1

是的,@ user3084341,你需要使用$ this->來引用一個類變量! –

1

$isDealer並不意味着$this->isDealer。它意味着一個新的,隱式創建的變量。

另外,你不能重寫那樣的成員變量。

1

當你寫

if ($isDealer) 

你不檢查您所期望的變量的值。您的代碼詢問函數dealCards()範圍內的變量$isDealer是否存在或是真/假。爲了檢查類Person的成員變量$isDealer是否爲true/false,您必須使用$this->isDealer。這可確保您檢查Person範圍內的成員變量$isDealer,而不在成員函數的範圍內。所以,你應該得到,如果你使用

if ($this->isDealer) 
0

你所期望的行爲,當你有這樣一行:

class Dealer extends Person { public $isDealer = true; } 

是有可能,public $isDealer = true;將覆蓋類Person {}的public $isDealer,擁有它是$ isDealer永遠是真的?從另一個角度來看,如果這個腳本是您使用$ isDealer的唯一地方,那麼將它定義爲public可能並不是真的有必要嗎?