Take a closer look at the differences between interfaces and abstract classes in php

  • 2020-06-07 04:07:44
  • OfStack

Interfaces and abstract classes are really hard to distinguish, citation they are very similar, methods have no defined logic, and both are intended or inherited by subclasses. To distinguish between the two, just remember one sentence: interfaces are specifications and classes are implementations. The purpose of an interface is to define a specification that everyone follows.

That is, interfaces and abstract classes can be clearly distinguished from each other by purpose. So the question remains, if you have an excuse, why do you have to have abstract classes?

Add a class named Animal that has two subsets of Dog and Cattle, and both have two methods: run() and speak().

Assume that the "run (run)" of Dog and Cattle are the same, so the run() method has the same business logic. "Called (speak)" is different, so the business logic of the speak() method is different. In addition, there is an IAnimal interface that requires both methods, which means that the Animal class must implement both methods. Similarly, are the subclasses Dog and Cattle required to implement both methods?

<?php
interface IAnimal{
 public function run();
 public function speak();
}
class Animal implements IAnimal{
 public function run(){
  // You can add it here 1 Some of the same run logic 
  return "same run<br />";
 }
 public function speak(){
  // I can add in here 1 Some of the same speak logic 
  return "same speak<br />";
 }
}
class Dog extends Animal{
 public function speak(){
  // You can add it here 1 some Dog logic 
  return "Dog speak<br />";
 }
}
class Cattle extends Animal{
 public function speak(){
  // You can add it here 1 some Cattle logic 
  return "Cattle speak<br />";
 }
}
$oDog=new Dog();
echo($oDog->run());
echo($oDog->speak());
$oCattle=new Cattle();
echo($oCattle->run());
echo($oCattle->speak());
?>


Related articles: