本文介绍了类中接口的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编写类时接口的目的是什么?
what is the purpose of interface when writing a class?
这是我在网上看到的一个例子.
heres an example i've seen online.
<?php
interface Chargeable {
public function getPrice();
}
class Employee implements Chargeable {
protected $price;
public function getPrice() {
return $this->price;
}
}
$product = new Employee();
?>
推荐答案
这是我了解接口并理解它们的方法之一.
Here is one of the ways how I learned about interfaces and understood them.
想象一下这种情况:
abstract class Plane {
public function openDoors();
}
interface Fliers {
public function fly();
}
现在让我们使用它们:
class Boeing747 extends Plane implements Fliers {
public function fly() {
// some stuff
}
public function openDoors() {
// do something
}
}
并且:
class Tweety implements Fliers{
public function fly() {
// some stuff
}
}
波音747是可以飞的飞机,而特威蒂是可以飞的鸟,但是对于特威蒂来说,"openDoors"是没有意义的.
Boeing747 is Plane that can fly and Tweety is a bird than can fly but it makes no sense for Tweety to "openDoors".
重点是接口可以由不同种类的对象实现,而类则不能.如您所见,波音747和Tweety除了可以飞行外没有其他共同点.
The point is that interfaces can be implemented by different kinds of objects but classes can not. As you can see Boeing747 and Tweety have nothing in common other than both can fly.
这篇关于类中接口的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!