1

我是一个新手,试图设计一个计算学生分数的应用程序。我正在尝试使用 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";


 }
 }
 }

现在我试图在下面的其他 php 中调用变量我的意思是 $totalscore 和 $grade

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";
   }
   }
4

2 回答 2

1
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

于 2013-01-10T22:03:33.747 回答
0

使用您的课程时,您正确地调用了这样的方法:

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

类的变量(通常称为成员或属性)的调用方式类似(假设它们是公共的):

if($fun->totalscore > 100){
    echo "invalid score";
}
于 2013-01-10T22:00:01.953 回答