2017-02-27 15 views
-2
<?php 
class Dribble { 
    public $shotCount = 0; 
    private $shot = false; 
    public function shotPosted() { 
     $shot = true; 
     if ($shot == true) { 
      $shotCount++; 
      echo $shotCount; 
     } 
     if ($shotCount >= 7) { 
     exit("You've reached your monthly goal!"); 
     } 
    } 
} 
$shot1 = new Dribble(); 
$shot1->shotPosted(); 
$shot2 = new Dribble(); 
$shot2->shotPosted(); 

我對面向對象的PHP有點新,我目前正在研究一個有點困難的問題。 任何輸入將不勝感激。先謝謝你。面向對象的計數器

+0

'if($ shot = true)'應該是'if($ shot == true)'。 '='是賦值,'=='是比較。 – Barmar

+0

你需要爲你的函數 – cmorrissey

回答

-1

對於本 -

if ($shot = true) { ... } 

你大概的意思是這樣的:

if ($shot == true) { ... } 

=爲賦值,==是測試平等; ===同等類型的測試。

+0

中的所有實例使用'$ this-> shotCount',而這是他的代碼中的錯誤,而不是問題或答案 – cmorrissey

+0

他實際上沒有說他的問題是什麼,所以我們是左猜... –

0

要訪問該對象的屬性,必須在該方法中使用->表示法。所以$shotCount應該是$this->shotCount

class Dribble { 
    public $shotCount = 0; 
    public function shotPosted() { 
     $this->shotCount++; 
     echo $this->$shotCount; 
     if ($this->$shotCount >= 7) { 
     echo "You've reached your monthly goal!"; 
     $this->shotCount = 0; 
     } 
    } 
} 

你也不應該在函數中調用exit()。說明中指出shotCount應該設置爲0,但是當您退出腳本時,您將失去一切。