简体   繁体   English

PHP 在扩展时用另一个类替换扩展

[英]PHP replace extends with another class when extending

Let's take the following class structure:让我们采用以下类结构:

class A {
    ... has all the functionalities of A
}

class B extends A {
   ... has all the functionalities of A and B
}

And these two other class structures:还有另外两个类结构:

class C extends B {
   ... has all the functionalities of A and B and C
}

class D extends A {
    ... all the functionalities of A, and D
}

how could I create a class easily, that would gain all the functionalities of all four of my classes, if I am not allowed to modify class A or class B ?如果不允许我修改class A class Bclass B类,我如何轻松创建一个类,这将获得我所有四个类的所有功能? Would something like this be possible with PHP ? PHP可以实现这样的功能吗?

EDIT:编辑:

The reason I would like to do this is the following, I am open for suggestions on other ways my desired outcome can be achieved:我想这样做的原因如下,我愿意就其他可以实现我想要的结果的方式提出建议:

I have a module, which has several classes on which I plan to build on, and I do not want to edit the module directly, but I would like to add functionalities potentially to multiple classes of this module (this is where class A and class B is coming from).我有一个模块,它有几个我计划在其上构建的类,我不想直接编辑该模块,但我想向该模块的多个类添加潜在的功能(这是class A class Bclass B来自)。

So to edit class A , I would create a class D , which extends it, and add new functionalities, or rewrite already added functionalities that needs rewrite in class D .所以要编辑class A ,我会创建一个class D ,它扩展它,并添加新功能,或者重写已经添加的需要在class D重写的功能。

But there are multiple classes in this module, which are simmilar in structure to class B , which I would also like to potentially modify, hence my class C .但是这个模块中有多个类,它们在结构上与class B相似,我也想潜在地修改它,因此我的class C But if I modified the modules class A in my class D , I would need my new class C to extend the class D instead of the class A .但是如果我修改了class D的模块class A ,我将需要我的新class C来扩展class D而不是class A (hope you can still follow me:P) (希望你还可以关注我:P)

No, in PHP it is not possible to inherit from multiple parents due to " Dimond Problem ".不,在 PHP 中,由于“ 钻石问题”,不可能从多个父代继承。 In your case, this means you can extend c for the functionality of a, b & c , but you cannot extend d too.在您的情况下,这意味着您可以扩展c以实现a, b & c ,但您也不能扩展d Since you cannot modify the other classes, there is not right solution here, but I'd recommend looking into traits ( https://www.php.net/manual/en/language.oop5.traits.php ), as these allow you to 'inherit' from multiple traits.由于您无法修改其他类,因此这里没有正确的解决方案,但我建议您查看特征( https://www.php.net/manual/en/language.oop5.traits.php ),因为这些允许你从多个特征“继承”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM