Skip to content
Advertisement

Transform a average php code to OOP (set_get) [closed]

I have this code I want to Transform to OOP (Set-Get) what the code do is to take some numbers and find the average.

function average($array)
{
    foreach ($array as $item) {
        $total += $item;
    }
    return $total / count($array);
}

$array = array(1, 2, 5, 7, 8, 6, 4);
echo average($array);

it`s my first time learning this i need to do it with class (set/get) : this what i did i:

class exm
{
    public $average;
    public $array;
    public $total;

    public function set_average($average)
    {
        $this->average = $average;

        foreach ($array as $item) {
            $total += $item;
        }
    }

    public function get_average()
    {
        return $total / count($array);
    }
}

$sa = new exm();
$sa->set_average(2, 2, 2, 4, 7, 6);
echo $sa->get_average();

Advertisement

Answer

A non-complete definition (but all you need to know for this example):
In object oriented programming (OOP) classes are used to link/group together data and its behavior / operations you can do with that specific data. OOP is not set/get!!!

In your specific case the data is an array of numbers and the operation is the average calculation. Another operation would be the total calculation.

Very basic example of what you need:

<?php

class exm {
    private $array = [];
    
    public function setArray($array) {
        $this->array = $array;
    }
    
    public function calculateTotal() {
        $total = 0;
        foreach($this->array as $item) {
            $total += $item;
        }
        return $total;
    }
    
    public function count() {
        return count($this->array);
    }
    
    public function calculateAverage() {
        return $this->calculateTotal() / $this->count();
    }
}

$exm = new exm();
$exm->setArray([1, 2, 3, 4]);
var_dump($exm->calculateAverage());

Further on, other operations can be added to your class. For example, when you want to append additional numbers to the original array (method appendItem()):

<?php

class exm {
    private $array = [];
    
    public function setArray($array) {
        $this->array = $array;
    }
    
    public function calculateTotal() {
        $total = 0;
        foreach($this->array as $item) {
            $total += $item;
        }
        return $total;
    }
    
    public function count() {
        return count($this->array);
    }
    
    public function calculateAverage() {
        return $this->calculateTotal() / $this->count();
    }

    public function appendItem($item) {
        $this->array[] = $item;
    }
}

$exm = new exm();
$exm->setArray([1, 2, 3, 4]);
var_dump($exm->calculateAverage());

$exm->appendItem(5);
var_dump($exm->calculateAverage());

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement