接口允许您创建定义实现接口的类的方法的代码。但是,您不能向这些方法添加任何代码。

抽象类允许您做同样的事情,同时向方法添加代码。

现在,如果可以用抽象类实现同样的目标,我们为什么还需要接口的概念呢?

有人告诉我,这与从c++到Java的面向对象理论有关,这也是PHP面向对象的基础。这个概念在Java中有用而在PHP中没有吗?这仅仅是一种避免在抽象类中布满占位符的方法吗?我遗漏了什么吗?


当前回答

我不了解其他语言,界面的概念是什么。但对于PHP,我将尽力解释。耐心点,如果有帮助请评论。

接口就像“契约”一样工作,指定一组子类做什么,但不指定它们如何做。

规则

An Interface can't be instantiate. You can't implement any method in an interface,i.e. it only contains .signature of the method but not details(body). Interfaces can contain methods and/or constants, but no attributes. Interface constants have the same restrictions as class constants. Interface methods are implicitly abstract. Interfaces must not declare constructors or destructors, since these are implementation details on the class level. All the methods in an interface must have public visibility.

现在让我们举个例子。 假设我们有两个玩具:一个是狗,另一个是猫。

正如我们所知,狗叫,猫叫。这两者具有相同的说话方法,但具有不同的功能或实现。 假设我们给用户一个带有说话按钮的遥控器。

当用户按下说话按钮时,玩具必须说话,无论它是狗还是猫。

这是使用接口而不是抽象类的好情况,因为实现是不同的。 为什么?还记得

如果您需要通过添加一些非抽象方法来支持子类,则应该使用抽象类。否则,接口将是您的选择。

其他回答

界面就像你的基因。

抽象类就像你实际的父母。

它们的目的是遗传的,但是在抽象类和接口的情况下,继承的是更具体的。

这个概念在面向对象编程中非常有用。对我来说,我认为接口是一种契约。只要我的类和你的类同意这个方法签名合同,我们就可以“接口”。至于抽象类,我认为更多的是存根一些方法的基类,我需要填充细节。

下面是PHP接口的要点

It is used to define required no of methods in class [if you want to load html then id and name is required so in this case interface include setID and setName]. Interface strictly force class to include all the methods define in it. You can only define method in interface with public accessibility. You can also extend interface like class. You can extend interface in php using extends keyword. Extend multiple interface. You can not implement 2 interfaces if both share function with same name. It will throw error.

示例代码:

interface test{
    public function A($i);
    public function B($j = 20);
}

class xyz implements test{
    public function A($a){
        echo "CLASS A Value is ".$a;
    }
    public function B($b){
        echo "CLASS B Value is ".$b;
    }
}
$x = new xyz();
echo $x->A(11);
echo "<br/>";
echo $x->B(10);

接口本质上是您可以创建的内容的蓝图。它们定义了类必须具有的方法,但是您可以在这些限制之外创建额外的方法。

我不确定你所说的不能向方法添加代码是什么意思——因为你可以。您是将接口应用到抽象类还是扩展它的类?

应用于抽象类的接口中的方法需要在该抽象类中实现。然而,将该接口应用于扩展类,该方法只需要在扩展类中实现。在这里我可能错了——我没有尽可能多地使用接口。

我一直认为接口是外部开发人员的一种模式,或者是确保事情正确的额外规则集。

接口的全部意义在于为您提供灵活性,使您的类强制实现多个接口,但仍然不允许多重继承。从多个类继承的问题很多,维基百科的页面很好地总结了这些问题。

接口是一种折衷。关于多重继承的大多数问题并不适用于抽象基类,所以现在大多数现代语言禁用多重继承,但却调用抽象基类接口,并允许一个类“实现”任意数量的抽象基类。