【问题标题】:PHP OOP what is the exact usage of interface? [duplicate]PHP OOP 接口的具体用法是什么? [复制]
【发布时间】:2012-12-25 22:55:03
【问题描述】:

可能重复:
Interface vs Abstract Class (general OO)
Interface or an Abstract Class: which one to use?

我对@9​​87654323@ 有几个问题:

如果interface 可以作为实现它的类的一种蓝图,为什么不改用abstract parent classes?

在什么情况下使用interface 而不是abstract class 更合适?

在什么情况下使用abstract class 而不是interface 更合适?

interface的具体用法是什么?

【问题讨论】:

标签: php oop abstract-class abstract


【解决方案1】:

一个很大的区别是你不能扩展多个抽象类,但你可以实现多个接口。

所以这样一来,对象如果实现了多个接口,就可以有多种用途,并且可以在各种不同的场景中使用。

所以为了让这更具体...

interface Wine{
   function isPeppery();
}

interface Dessert{
   function hasBerries(){
}

class PortWine implements Wine, Dessert{
   function isPeppery(){
     returns false;
   }
   function hasBerries(){
     returns true;
   }
}

class BlackForestCake implements Dessert{
   function hasBerries(){
      returns true;
   }
 }

通过这种方式,您可以在整个应用程序中拥有用于多种用途的对象。

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2020-11-09
    • 2011-02-25
    • 2012-05-30
    • 1970-01-01
    • 2012-03-25
    相关资源
    最近更新 更多