无法实现具有相同方法名称的两个接口 [英] Cannot implement two interfaces that have the same method name

查看:103
本文介绍了无法实现具有相同方法名称的两个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不起作用:

interface TestInterface
{
    public function testMethod();
}

interface TestInterface2
{
    public function testMethod();
}

class TestClass implements TestInterface, TestInterface2
{

}

给我错误:


致命错误:无法继承抽象函数TestInterface2: :testMethod()(之前在TestInterface中声明为abstract)。

Fatal error: Can't inherit abstract function TestInterface2::testMethod() (previously declared abstract in TestInterface).

这是正确的吗?为什么不允许这样做?对我来说没有意义。

Is that correct? Why is this not allowed? Doesn't make sense to me.

抽象函数也会发生这种情况,例如,如果你实现了一个接口,然后从一个具有抽象函数的类继承它。同名。

This also happens with abstract functions, for example if you implement an interface and then inherit from a class that has an abstract function of the same name.

推荐答案

实现包含具有相同签名的方法的两个接口是没有意义的。

It makes no sense to implement two interfaces containing methods with the same signatures.

编译器无法知道方法是否实际具有相同的目的 - 如果不是,则意味着至少有一个接口不能由您的类实现。

The compiler cannot know if the methods actually have the same purpose - if not, it would mean that at least one of the interfaces cannot be implemented by your class.

示例:

interface IProgram { function execute($what); /* executes the given program */ }
interface ISQLQuery { function execute($what); /* executes the given sql query */ }

class PureAwesomeness implements IProgram, ISQLQuery {
    public function execute($what) { /* execute something.. but what?! */ }
}

如你所见,这两种方法都不可能实现接口 - 并且也不可能从给定的接口调用实际实现该方法的方法。

So as you see, it's impossible to implement the method for both interfaces - and it'd also be impossible to call the method which actually implements the method from a given interface.

这篇关于无法实现具有相同方法名称的两个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆