【问题标题】:How to create an interface composed of other interfaces?如何创建一个由其他接口组成的接口?
【发布时间】:2012-12-06 05:38:36
【问题描述】:

我想创建一个接口IFoo,它基本上是自定义接口IBar 和一些本机接口ArrayAccessIteratorAggregateSerializable 的组合。 PHP 似乎不允许实现其他接口的接口,因为我在尝试时收到以下错误:

PHP 解析错误:语法错误,意外的 T_IMPLEMENTS,在 Y 行的 X 中预期为“{”

我知道接口可以扩展其他接口,但是 PHP 不允许多重继承,我不能修改原生接口,所以现在我卡住了。

我是否必须复制 IFoo 中的其他接口,还是有更好的方法可以让我重用原生接口?

【问题讨论】:

  • 您尚未发布任何与错误相关的代码。但你应该这样做。

标签: php interface


【解决方案1】:

你需要使用extends关键字来扩展你的接口,当你需要在你的类中实现接口时,你需要使用implements关键字来实现它。

您可以在班级中的多个接口上使用implements。如果你实现了接口,那么你需要定义所有函数的主体,像这样......

interface FirstInterface
{
    function firstInterfaceMethod1();
    function firstInterfaceMethod2();
}
interface SecondInterface
{
    function SecondInterfaceMethod1();
    function SecondInterfaceMethod2();
}
interface PerantInterface extends FirstInterface, SecondInterface
{
    function perantInterfaceMethod1();
    function perantInterfaceMethod2();
}


class Home implements PerantInterface
{
    function firstInterfaceMethod1()
    {
        echo "firstInterfaceMethod1 implement";
    }

    function firstInterfaceMethod2()
    {
        echo "firstInterfaceMethod2 implement";
    }
    function SecondInterfaceMethod1()
    {
        echo "SecondInterfaceMethod1 implement";
    }
    function SecondInterfaceMethod2()
    {
        echo "SecondInterfaceMethod2 implement";
    }
    function perantInterfaceMethod1()
    {
        echo "perantInterfaceMethod1 implement";
    }
    function perantInterfaceMethod2()
    {
        echo "perantInterfaceMethod2 implement";
    }
}

$obj = new Home();
$obj->firstInterfaceMethod1();

等等……调用方法

【讨论】:

  • 请避免发布重复的答案。您应该有充分的理由在 6 年后发布答案。
【解决方案2】:

您正在寻找extends 关键字:

Interface IFoo extends IBar, ArrayAccess, IteratorAggregate, Serializable
{
    ...
}

Object Interfaces,具体见Example #2 Extendable Interfaces ff

【讨论】:

  • @Neal 请访问php.net/manual/en/language.oop5.interfaces.php 并找到示例#3 多接口继承
  • 允许扩展多个接口。如果在其中两个或多个中声明了相同的方法,它就会失败。
  • @joequincy:在哪个 PHP 版本中?不在当前稳定的 PHP 版本中。然而,从 same 接口多次 扩展是一个错误条件(这是有道理的)。
  • 嗯。我很可能只是过时了。
  • 哇,谢谢你教我 RTFM。我只是假设,因为你不能用类继承来扩展多个类,你也不能用接口继承。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 2019-08-18
  • 2021-07-15
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多