Ad

A couple who work on a farm have asked you to create a program for them that will allow to them store the types of animals they have on the farm, these include:

-Cows
-Chickens
-Pigs

Using interfaces we can make the process of creating the classes for each animal easier. By using an animal interface we can group the animals together in the code.

interface AnimalsInterface
{
    public function getLegs();
    public function setLegs($noOfLegs);
    public function getDiet();
    public function setDiet($foodTheyEat);
}

class Cow implements AnimalsInterface
{
    private $legs;
    private $diet;
    
    public function getLegs()
    {
        return $this->legs;
    }
    public function setLegs($noOfLegs)
    {
        $this->legs = $noOfLegs;
        return $this;
    }
    public function getDiet()
    {
        return $this->diet;
    }
    public function setDiet($foodTheyEat)
    {
        $this->diet = $foodTheyEat;
        return $this;
    }
}

class Chicken implements AnimalsInterface
{
    private $legs;
    private $diet;
    
    public function getLegs()
    {
        return $this->legs;
    }
    public function setLegs($noOfLegs)
    {
        $this->legs = $noOfLegs;
        return $this;
    }
    public function getDiet()
    {
        return $this->diet;
    }
    public function setDiet($foodTheyEat)
    {
        $this->diet = $foodTheyEat;
        return $this;
    }
}

class Pig implements AnimalsInterface
{
    private $legs;
    private $diet;
    
    public function getLegs()
    {
        return $this->legs;
    }
    public function setLegs($noOfLegs)
    {
        $this->legs = $noOfLegs;
        return $this;
    }
    public function getDiet()
    {
        return $this->diet;
    }
    public function setDiet($foodTheyEat)
    {
        $this->diet = $foodTheyEat;
        return $this;
    }
}

class Farm
{
    private $animals = [];
    
    public function addAnimal(AnimalsInterface $animal)
    {
        array_push($this->animals, $animal)
    }
    public function displayAnimals()
    {
        foreach($this->animals as $animal) {
            echo $animal->getLegs();
            echo $animal->getDiet();
        }
    }
}

$cow = new Cow();
$cow->setLegs(4)->setDiet('Grass');
$chicken = new Chicken();
$chicken->setLegs(2)->setDiet('Seeds');
$pig = new Pig();
$pig->setLegs(4)->setDiet('Corn');
$farm = new Farm;
$farm->addAnimal($cow);
$farm->addAnimal($chicken);
$farm->addAnimal($pig);
$farm->displayAnimal();