带接口的 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.
有什么我遗漏的吗?
推荐答案
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() { }
}
但是请注意,您必须实现接口并使用 trait(或者,当然,提供您自己的实现).并且 C 和 D 完全没有关系,除了两者都实现了 A 接口.Traits 基本上只是解释器级别的复制粘贴,不影响继承.
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.
相关文章