Class C extends B. And class B extends either A1 or A2, depending on an argument of C’s constructor. How to define class A, B and C?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Like deceze already points out, this is not possible with inheritance.
You could use PECL’s
runkit_class_adoptto convert a base class to an inherited class, add ancestral methods when appropriate but runkit is something you dont want in your production code.The clean OO approach to this would be to use a Bridge pattern to give the object the implementation of the A class at runtime and thereby
How it works
First define an interface every "parent" of B and B itself has to implement. The interface should contain all the methods you want B to"inherit". I am putting these terms in quotes, because technically they are neither parents, nor inheriting anything.
Then define classes A1 and A2 implementing this interface and add the methods demanded by the interface.
Next create your class B and make it require one of the implementing classes on initialization.
As you can see, any calls to the methods required by our interface are delegated to the aggregated "parent" object, so depending on what you passed into B, you will get different results.
Now to define C we just make it accept the class name of the implementation class and instantiate it within C to pass it to the parent, e.g. B.
and then you can do