3

So, I have two classes. I am wondering if I can have two types of objects of Class A:

  1. normal objects of Class A,
  2. objects of class A that inherit Class B's behavior whilst retaining their own,

without creating a third Class.

Is this possible?

Class A in its basic form does not have all the features of Class B, therefore extending Class B is not an option.

I am using PHP btw.

holographic-principle
  • 19,688
  • 10
  • 46
  • 62
  • 1
    You are looking for a mixin. See http://stackoverflow.com/questions/6876925/is-it-possible-to-use-mixins-in-php – John Dvorak Oct 25 '12 at 05:05
  • Thanks, I'll check out Traits in PHP 5.4+ – holographic-principle Oct 25 '12 at 05:12
  • You could theoretically do something along these lines with traits, or with object composition (instances of class B may or may not have an instance of class A as a property). I would wonder about the design you're trying to implement though, especially if you go the Trait route, as it sounds like you're trying to implement a design that doesn't fit well with good OOP practice. – GordonM Oct 25 '12 at 06:55
  • I settled for the following: 1. classes A,B,C extend abstract class X; 2. class A uses trait 1; 3. class B uses trait 2; 4. class C uses trait 1,2. It's more DRY than what I could've done without traits, although not exactly what I was originally looking for. Any better suggestions? – holographic-principle Oct 25 '12 at 07:14
  • Class C is actually "A with B", but I chose to go with "C uses trait 1,2" (trait 1 was introduced for this purpose) rather than "C extends class A, uses trait 2" to have better control over inherited methods, due to the precedence rules with traits. Ultimately, I store all 3 types in the same collection and treat them as subtypes. – holographic-principle Oct 25 '12 at 07:21
  • Can you post an answer to your question then? Otherwise this will remain unanswered. – jdstankosky Nov 09 '12 at 17:42

1 Answers1

0

So, what I discovered was that if you want a certain behavior to be shared between different classes (horizontally), this is possible in PHP 5.4+ with the use of traits.

For example, you can define a trait called 'Driving' and various types of Driver actors can implement it.

The classes implementing traits will inherit all the properties and methods of the trait, and those properties and methods will appear as part of the class even when using reflection.

Here's a useful link that explains it well.

holographic-principle
  • 19,688
  • 10
  • 46
  • 62