2013-01-10 32 views
0

我是一個試圖設計計算學生分數的應用程序的新手。我試圖用OOP來簡化我的工作,並且在這裏一直有錯誤。這是我做了類:如何在類中調用變量

class fun { 
var $totalscore; 
public function score($assignment,$cat,$exam){ 

     return $totalscore = $assignment+$cat+$exam; 

     if($totalscore <=100 && $totalscore >=70){ 
      return $grade = "A"; 
     } 
     elseif($totalscore <=69 && $totalscore>=60){ 
      return $grade = "B"; 
     } 
     elseif($totalscore <=59 && $totalscore>=50){ 
      return $grade = "C"; 
     } 
     elseif($totalscore <=35 && $totalscore>=49){ 
      return $grade = "D"; 
     } 
     elseif($totalscore <=40 && $totalscore>=34){ 
      return $grade = "E"; 
     } 
     elseif($totalscore <=39 && $totalscore>=0){ 
     return $grade = "F"; 


} 
} 
} 

現在我試着打電話給我的意思是$ totalscore和$級變量在我的其他PHP下面

if(isset($_POST['update'])){ 
    $gnsa = $_POST['gnsa']; 
    $gnst =$_POST['gnst']; 
    $gnse =$_POST['gnse']; 
    $agidi =$_POST['matric']; 

    include ("class.php"); 
    $fun = new fun; 
    $fun-> score($gnsa,$gnst,$gnse); 
    if($totalscore > 100){ 
    echo "invalid score"; 
    } 
    } 
+0

您收到的錯誤是什麼? – crush

+2

選擇一本PHP /編程書籍並瞭解更多信息 - 這會更好地幫助您 – codingbiz

+0

退一步,思考功能是如何工作的。您不能從調用代碼訪問函數的局部變量。另外,當函數內部有'return'語句時,下面的語句不會被執行。您應該先閱讀其中一個或另一個教程。 –

回答

0
class fun 
{ 
    // notice these 2 variables... they will be available to you after you 
    // have created an instance of the class (with $fun = new fun()) 
    public $totalscore; 
    public $grade; 

    public function score($assignment, $cat, $exam) 
    { 
     $this->totalscore = $assignment + $cat + $exam; 

     if ($this->totalscore >= 70) { 
      $this->grade = "A"; 
     } 
     else if ($this->totalscore <= 69 && $this->totalscore >= 60) { 
      $this->grade = "B"; 
     } 
     else if ($this->totalscore <= 59 && $this->totalscore >= 50) { 
      $this->grade = "C"; 
     } 

     else if ($this->totalscore <= 35 && $this->totalscore >= 49) { 
      $this->grade = "D"; 
     } 

     // there is probably something wrong here... this number (40) shouldn't 
     // be higher than the last one (35) 
     else if ($this->totalscore <= 40 && $this->totalscore >= 34) { 
      $this->grade = "E"; 
     } 
     else { 
      $this->grade = "F"; 
     } 
    } 
} 

,你做$fun->score($gnsa,$gnst,$gnse);後,您將能夠分別$fun->totalscore$fun->grade訪問總分和等級。

+0

非常感謝代碼工作。我真的很感激。 –

+0

不客氣! – glomad

0

當使用類,你是正確調用方法像這樣:

$fun->score($gnsa,$gnst,$gnse); 

變量(通常稱爲成員或屬性)的一類被稱爲只是同樣(只要它們是公開的):

現在
if($fun->totalscore > 100){ 
    echo "invalid score"; 
}