带接口的PHP多重继承 [英] PHP Multiple Inheritance with Interfaces

查看:134
本文介绍了带接口的PHP多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解如何使用接口为我提供多重继承,因为我一直在谷歌搜索。

I'm trying to understand how using interfaces gives me multiple inheritance as I've been googling.

class A
{
 function do1(){}
 function do2(){}
 function do3(){}
}

class B extends A
{
 function do4(){}
 function do5(){}
 function do6(){}
}

class C extends B
{
}

在上面的例子中,C类有A类和B类的所有方法。但是,B类也有A类的所有方法,这是不必要的。

In the above example, class C has all the methods from class A and B. However, class B also has all the methods of class A, which is not necessary desired.

我的搜索已经开始使用了通过将方法移动到类并创建接口来解决此问题的接口,如下所示。

My searches have come up to use interfaces to solve this issue by moving methods to a class and creating interfaces, as below.

interface A
{
     function do1();
     function do2();
     function do3();
}

interface B
{
     function do4();
     function do5();
     function do6();
}

class C implements A, B
{
     function do1(){}
     function do2(){}
     function do3(){}
     function do4(){}
     function do5(){}
     function do6(){}
}

我真的没有看到这是如何解决这个问题的,因为所有代码都在新类中。如果我只是想最初使用A类,我将不得不创建一个实现接口A的新类,并将相同的代码复制到新类中。

I don't really see how this solves the issue because all the code is in the new class. If I just wanted to use class A as originally, I would have to create a new class that implement interface A and copy the same code to the new class.

是否存在我缺少的东西?

Is there something I'm missing?

推荐答案

PHP没有多重继承。但是,如果你有PHP 5.4,你可以使用 traits 来至少避免每个课程复制代码。

PHP doesn't have multiple inheritance. If you have PHP 5.4, though, you can use traits to at least avoid every class having to copy code.

interface A {
    public function do1();
    public function do2();
    public function do3();
}

trait Alike {
    public function do1() { }
    public function do2() { }
    public function do3() { }
}


interface B {
    public function do4();
    public function do5();
    public function do6();
}

trait Blike {
    public function do4() { }
    public function do5() { }
    public function do6() { }
}


class C implements A, B {
    use Alike, Blike;
}

class D implements A {
    use Alike;

    // You can even "override" methods defined in a trait
    public function do2() { }
}

但是,请注意,您必须实现接口并使用特征(或者,当然,提供您自己的实现)。除了实现A接口外,C和D根本没有关系。特征基本上只是解释器级别的复制和粘贴,不会影响继承。

Note, though, you have to both implement the interface and use the trait (or, of course, provide your own implementation). And C and D are not related at all, except in both implementing the A interface. Traits are basically just interpreter-level copy and paste, and do not affect inheritance.

这篇关于带接口的PHP多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆