64

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

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

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

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

4

2 回答 2

126

您正在寻找extends关键字:

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

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

于 2012-12-18T22:47:33.210 回答
7

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

等等...调用方法

于 2018-09-12T09:38:47.527 回答