Home  >  Article  >  Backend Development  >  Code example analysis: What is the difference between PHP interface and abstract class?

Code example analysis: What is the difference between PHP interface and abstract class?

伊谢尔伦
伊谢尔伦Original
2017-07-03 09:31:281148browse

This article is a detailed analysis and introduction to the difference between interface and abstract class in php. Friends who need it can refer to

Interface and abstract class It's really hard to distinguish them. They are very similar. The methods have no defined logic. They are all for subclasses to inherit or . To distinguish between the two, just remember one sentence: The interface is the specification, and the class is the implementation. The purpose of the interface is to define a specification that everyone follows.
In other words, interfaces and abstract classes can be clearly distinguished from each other in terms of purpose. So there is still a question, since there is an excuse, why is there still an abstract class?

Join us to define a class named Animal, which has two subsets Dog and Cattle, both of which have two methods: run() method and speak() method.

Assume that the "run" of Dog and Cattle is the same, so the run() method has the same business logic; and the "speak" is different, so the business logic of the speak() method The logic is different. Moreover, there is an IAnimal interface that stipulates that these two methods must be present, which means that the Animal class must implement these two methods. Similarly, the two subclasses Dog and Cattle must also have these two methods, then we can define it like this :

The code is as follows:

<?php
interface IAnimal{
 public function run();
 public function speak();
}
class Animal implements IAnimal{
 public function run(){
  //在这里可以添加一些相同的run逻辑
  
return
 "same run<br />";
 }
 public function speak(){
  //这里可以添加一些相同的speak逻辑
  return "same speak<br />";
 }
}
class Dog 
extends
 Animal{
 public function speak(){
  //在这里可以添加一些Dog逻辑
  return "Dog speak<br />";
 }
}
class Cattle extends Animal{
 public function speak(){
  //在这里可以添加一些Cattle逻辑
  return "Cattle speak<br />";
 }
}
$oDog=new Dog();
echo($oDog->run());
echo($oDog->speak());
$oCattle=new Cattle();
echo($oCattle->run());
echo($oCattle->speak());
?>

The above is the detailed content of Code example analysis: What is the difference between PHP interface and abstract class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn