I want to load 2 objects from my DB. The first object is the parent and second inherit of the first (in PHP and DB).
I've created 2 class : (it's only a sample not the real code so don't try to correct this ;-) )
class A{
...
public static function get($id){
$query = "SELECT id,field1,field2 FROM table_A WHERE id = $id";
$result = request($query);
return load_object_A_instance($result);
}
...
}
class B extends A{
...
public static function get($id){
$query = "SELECT id,field3,field4 FROM table_B WHERE id = $id";
$result = request($query);
return load_object_B_instance($result);
}
...
}
I would instantiate object B with its own properties and with properties of object A in the "same" action. How can I do this ?
I've some ideas but I don't see how to implement them :
class B extends A{
...
public static function get($id){
$query = "SELECT id, field3, field4 FROM table_B WHERE id = $id";
$result = request($query);
$B = load_object_B_instance($result);
if($B != empty/null){
$B = merge(A::get($B->id),$B); // <== that's the part I don't know how to implement
}
return $B;
}
...
}
Edit : I found a first solution (it's not clean but ...)
echo $obj->name; //show: carlos
echo $obj2->lastname; //show: montalvo here
$obj_merged = (object) array_merge((array) $obj, (array) $obj2);
$obj_merged->name; //show: carlos
$obj_merged->lastname; //show: montalvo here;
Solution found here: How do I merge two objects?