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

问题描述 投票:39回答:2

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

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

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

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

php interface
2个回答
83
投票

您正在寻找extends关键字:

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

请参阅Object Interfaces和特定的Example #2 Extendable Interfaces ff


2
投票

您需要使用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();

等等...通话方法

© www.soinside.com 2019 - 2024. All rights reserved.