2013-01-10 31 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"; 
}