In-depth analysis of the differences between interfaces and abstract classes in php

Source: Internet
Author: User

It is really difficult to distinguish interfaces from abstract classes. They are very similar to each other, and there is no defined logic for methods. They are all intended or inherited for subclasses. To distinguish the two, just remember one sentence:Interfaces are standards and classes are implementations.The purpose of an interface is to define a specification that everyone complies.

That is to say, the objective can clearly understand the region-specific interface and abstract class. So I still have doubts, since there is an excuse, why must there be an abstract class?

In addition, we want to define a class named Animal, which has two subsets: Dog and Cattle. Both of them have two methods: run () and speak.

Assume that the "run" of Dog and Cattle are the same, so the run () method has the same business logic, while the "speak" method is different, therefore, the business logic of the speak () method is different. Moreover, there is an IAnimal interface that requires the two methods, which means that the Animal class must implement these two methods. Similarly, do Dog and Cattle subclasses must also have these two methods, we can define it as follows:
Copy codeThe Code is as follows:
<? Php
Interface IAnimal {
Public function run ();
Public function speak ();
}
Class Animal implements IAnimal {
Public function run (){
// Some identical run logic can be added here
Return "same run <br/> ";
}
Public function speak (){
// Some identical speak logic can be added here
Return "same speak <br/> ";
}
}
Class Dog extends Animal {
Public function speak (){
// Some Dog logic can be added here
Return "Dog speak <br/> ";
}
}
Class Cattle extends Animal {
Public function speak (){
// Some Cattle logic can be added here
Return "Cattle speak <br/> ";
}
}
$ ODog = new Dog ();
Echo ($ oDog-> run ());
Echo ($ oDog-> speak ());
$ OCattle = new Cattle ();
Echo ($ oCattle-> run ());
Echo ($ oCattle-> speak ());
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.