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

2022-08-30 08:57:58

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

PHP 解析错误:语法错误、意外T_IMPLEMENTS、X 行 Y 中出现“{”

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

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


答案 1

您正在寻找关键字:extends

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

请参阅对象接口和具体示例 #2 可扩展接口 ff


答案 2

您需要使用关键字来扩展接口,当您需要在类中实现接口时,则需要使用关键字来实现它。extendsimplements

您可以在类中使用多个接口。如果你实现接口,那么你需要定义所有函数的主体,就像这样......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();

等等...调用方法


推荐