如何创建由其他接口组成的接口?

FtD*_*Xw6 42 php interface

我想创建一个接口,IFoo即基本上是一个自定义接口的组合,IBar和一些原生接口,ArrayAccess,IteratorAggregate,和Serializable.PHP似乎不允许实现其他接口的接口,因为我在尝试时遇到以下错误:

PHP解析错误:语法错误,意外的T_IMPLEMENTS,在Y行的X中期望'{'

我知道接口可以扩展其他接口,但PHP不允许多重继承,我无法修改本机接口,所以现在我卡住了.

我是否必须复制其中的其他接口IFoo,或者是否有更好的方法允许我重用本机接口?

hak*_*kre 87

您正在寻找extends关键字:

Interface IFoo extends IBar, ArrayAccess, IteratorAggregate, Serializable
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

请参阅对象接口和特定示例#2可扩展接口ff.

  • 哇,谢谢你教我RTFM.我只是假设你不能用类继承扩展多个类,你也不能使用接口继承. (2认同)

fur*_*i89 5

你需要使用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();
Run Code Online (Sandbox Code Playgroud)

等等......调用方法