2013-12-09 58 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可能并不是真的有必要吗?