Home >Backend Development >PHP Tutorial >In-depth analysis of the difference between interfaces and abstract classes in PHP_PHP Tutorial

In-depth analysis of the difference between interfaces and abstract classes in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:08:01801browse

It is really difficult to distinguish between interfaces and abstract classes. They are very similar. The methods have no defined logic and are all intended or inherited by subclasses. To distinguish between the two, just remember one sentence: Interface is the specification, and 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 :

Copy code The code is as follows:

interface IAnimal{
public function run( );
public function speak();
}
class Animal implements IAnimal{
public function run(){
//You can add some same run logic here
return "same run
";
}
public function speak(){
//You can add some same speak logic here
return "same speak
";
}
}
class Dog extends Animal{
public function speak(){
//You can add some Dog logic here
return "Dog speak
" ;
}
}
class Cattle extends Animal{
public function speak(){
//You can add some Cattle logic here
return "Cattle speak
";
}
}
$oDog=new Dog();
echo($oDog->run());
echo($oDog->speak()) ;
$oCattle=new Cattle();
echo($oCattle->run());
echo($oCattle->speak());
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327491.htmlTechArticleIt’s really hard to distinguish between interfaces and abstract classes. The quotes are very similar, and the methods have no defined logic. For subclasses to want or inherit. To distinguish between the two, just remember one sentence: Interface is a specification...
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