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

伊谢尔伦
Release: 2023-03-12 12:32:02
Original
1218 people have browsed it

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());
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!