PHP Cascading Object Inheritance Defaults

I’m still new to some aspects of object oriented programming.  I’ve been stuck on this one problem for quite a bit now.  I’d like to build a hierarchy of objects, where the child object inherit’s it’s parents and grandparents default property.

It seemed like such a simple thing to do, but the more I messed with it, the more it boggled my mind.  I was trying to extend a base classes and merge the defaults while i add more information to every extended class.   Take for example the following code:

I wanted class C to have the defaults of all parent classes. The above code works and outputs:

Array ( [a] => A [b] => B [c] => C )

Thanks to Stephan Miller for helping me figure this out.

One thought on “PHP Cascading Object Inheritance Defaults”

  1. This seems a bit… I don’t want to say wrong, but it doesn’t feel quite right either.

    Why not pass your defaults array as an argument to __construct, merge them as you will at every subclass, but only letting the highest superclass write directly to defaults. This would give you the added benefit that a user of either class can pass their own defaults.

    Or implement a “setDefault” method on class A (probably protected), which you may call in the constructor of classes B and C. It just feels most right to let the class that defines a property take care of writing to it.

    And of course, you might want to actually add a “protected $defaults = Array()” to Class A ;-).

Leave a Reply