1

I have created an interface Animal and make function makeSound. Now I implements Animal in Cat and Dog class and echo something from makeSound function. Now I am confused why I need to create interface while I do the same task only create Cat and Dog class. Let see an example

With Interface

interface Animal{
  public function makeSound();
}

class Cat implements Animal{
  public function makeSound(){
    echo 'Meow';
  }
}

class Dog implements Animal{
  public function makeSound(){
    echo 'Geow';
  }
}

$cat = new Cat();
$cat->makeSound();
echo "<br>";

$dog = new Dog();
$dog->makeSound();
echo "<br>";

Without Interface

 class Cat{
    public function makeSound(){
    echo 'Meow';
    }
}

 class Dog{
    public function makeSound(){
    echo 'Geow';
    }
 }

$cat = new Cat();
$cat->makeSound();
echo "<br>";

$dog = new Dog();
$dog->makeSound();
echo "<br>";
Nazmul Hoque
  • 507
  • 4
  • 8
  • 1
    It's not relates to php, interface is a contract that some class should respect, code is more readable and understandable. In your use case, interface animal describe behavior of "Animal", and all animals make sound apparently, so if you create `Class Tiger` it should implements `Animal` because it would `makeSound()` too. It's a way to provide good quality in development. – Lounis Oct 16 '21 at 17:35
  • 1
    Because you're not doing a task where an interface would be useful – ADyson Oct 16 '21 at 17:36
  • https://stackoverflow.com/questions/1686174/when-should-one-use-interfaces explains more – ADyson Oct 16 '21 at 17:37
  • https://www.culttt.com/2014/04/02/code-interface also has a good example – ADyson Oct 16 '21 at 17:37
  • 2
    @Lounis, have a look at the links provided by@ADyson, they might help you sharpen your understanding of interfaces, IMHO. – jibsteroos Oct 16 '21 at 17:50

1 Answers1

0

Now you can add this:

class Vet
{
    public function callAnimal(Animal $animal)
    {
        $animal->makeSound();
    }
}

$jimmy = new Vet();
$lulu = new Cat();
$fido = new Dog();
$jimmy->callAnimal($lulu);
$jimmy->callAnimal($fido);

If you don't have an interface, you'd have to write:

$jimmy->callCat($lulu);
$jimmy->callDot($fido);

... and modify your Vet for every new animal you create.

Álvaro González
  • 135,557
  • 38
  • 250
  • 339