tags:

views:

216

answers:

2

Ok this is not just a PHP question, but I have this problem in PHP so I will post the example in PHP.

Example:

I have three classes, say, data_abstract, person, and student. Now, I have one array of data related to each of those objects.

class person extends data_abstract
{
    protected $data; //name, gender, etc
}

class student extends person
{
    protected $data; //student_id, etc
}

Now, assuming each of those "data" property is from database tables, for example, table_person, table_student.

Upon instantiation, we will parse the class name by get_class() function, and get data from their related tables.

class data_abstract
{
    public function __construct()
    {
        $name = get_class($this);
        $table = 'table_' . $name;

       $this->data = DB->query('SELECT * FROM ' . $table); 
       //whatever DB constant is, 
       //I'm just trying to get all rows of data from the related table.
    }
}

Ok, now the problem, when I instantiate student by $student = new student(); the constructor will get data from table_student for me and put it in $student->data, but I won't be able to get the data from table_person and put those two sets of data into one object.

By extending another class, we can have all the methods (functions) extended and customized (via polymorphism), but extending the attributes/properties of each level of object seems to be hard, at least without some manual construction.

Is there any way in the abstraction level to achieve this?

(thanks for reading, wish I could've made the question clearer.)

+1  A: 

Personally, I would put the database loading class in an protected method that takes one attribute - $tablename - and loads all the data. Then. in the constructer of the class call it by hand, and the parent.

class Person {
public function __construct() {
$this->loadData("Person");
}
}

Class Student extends Person {
public function __construct()
parent::__construct();
$this->loadData("Student");
}
}

Now, when you construct Student both data from Student and Person is loaded. if you use http://uk2.php.net/array_merge the 2 data arrays will be merged into one.

It's a matter of style; some people would critisise this by saying that you are now repeating something twice - more work to refactor - but I would say you are decoupling the class names and interfaces from the database design (a good thing) and with the parent call, the code is now more OO.

James
+2  A: 
e-satis