Disclaimer: This is not homework. Also, I’m describing a simplified situation so bear with my semi-psudo code.
I have what I feel is a pretty standard OOP situation, but I’m not sure the best way to handle it. Let’s say I have 3 classes: Base, A, and B. Class A extends Base and B extends A. The Base class’s constructor performs a database query that pulls various meta data defined in an array. See below:
Class Base {
public $meta_data = array('col1','col2');
function __construct() {
$db->query("select ".join(',',$this->meta_data)." from table");
}
}
Class A extends Base {
public $meta_data = array('col3','col4');
function _construct() {
parent::__construct();
}
}
Class B extends A {
public $meta_data = array('col5','col6');
function _construct() {
parent::__construct();
}
}
When I create a new B() object, I want the Base constructor’s sql query to look like this:
select col1, col2, col3, col4, col5, col6 from table;
And when I create a new Base() object, I want the sql query to look like this:
select col1, col2 from table;
Now…I technically know how to accomplish this (in possibly a crude way) but I’m curious what the proper way is without too much code replication and keeping in mind flexibility for the future (ie, adding a subclass of B). I basically need to merge the $meta_data arrays on each inheritance level all the way up to the constructor in the Base class.
Any ideas?
When you extend the class and define the new property you are overriding the values set in the parent class. I would wind up removing the
$meta_dataarray from all butBase. Then in your extending classes create a function similar to:After solving it in a very simple way I wound up deciding I would go with something like the following in
Base:Then in your extending class constructors you just pass in an array of the values you want to add to
Base::$meta_data.