简体   繁体   中英

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 ? Would something like this be possible with 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).

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 .

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 . 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 . (hope you can still follow me:P)

No, in PHP it is not possible to inherit from multiple parents due to " Dimond Problem ". In your case, this means you can extend c for the functionality of a, b & c , but you cannot extend d too. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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