Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

php - Cannot store array values into $sum

i made this student class

<?php 
Class Student

{
    private $name;
    private $amountOfGrades;
    private $grades=array();
    function __construct(string $name,int $amountOfGrades){
        $this->name=$name;
        $this->amountOfGrades=$amountOfGrades;
    }
    
    function setGrades(...$grade)
    {
        for($i=0;$i<$this->amountOfGrades;$i++)
        $this->grades[$i]=$grade;
    }
    function getGrades(){
        
        return $this->grades;
        
        
    }
 function getAvg(){
     $sum=0;
     for($i=0;$i<count($this->grades);$i++)
     $sum+=$this->grades[$i];
    return $sum/$amountOfGrades;
 }
}
?>

and this is where i test it

<?php
require_once "studentClass.php";

$Jack = new Student("Jack",3);
$Jack->setGrades(100,50,69);
print_r($Jack->getAvg());

?>

the problem is that i keep getting this error

Fatal error: Uncaught TypeError: Unsupported operand types: array + null in D:xamphtdocsstudentClass.php:27 Stack trace: #0 D:xamphtdocsestStudent.php(6): Student->getAvg() #1 {main} thrown in D:xamphtdocsstudentClass.php on line 27

how am i supposed to store the amount into sum to return the avg if i cant use += thanks in advance

question from:https://stackoverflow.com/questions/65875652/cannot-store-array-values-into-sum

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your setGrades was the problem, you passed the whole grade array to every single element. Also you have to use $this->amountOfGrades not $amountOfGrades. Take a look ;)

  <?php 
    Class Student
    
    {
        private $name;
        private $amountOfGrades;
        private $grades=array();
        
        function __construct(string $name,int $amountOfGrades){
            $this->name=$name;
            $this->amountOfGrades=$amountOfGrades;
        }
        
        function setGrades(...$grade)
        {
            for($i=0;$i<$this->amountOfGrades;$i++)
            $this->grades[$i]=$grade[$i];
        }
        
        function getGrades(){
            return $this->grades;
        }
        
         function getAvg(){
             $sum=0;
             for($i=0;$i<count($this->grades);$i++) {
                 $sum+=$this->grades[$i];
             }
             
             return $sum / $this->amountOfGrades;
         }
    }
    
    $Jack = new Student("Jack",3);
    $Jack->setGrades(100,50,69);
    print_r($Jack->getAvg());
    
    ?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...