Hello fellow programmer,
i want to pass a instance of the parents class to the childs constructor and instead of assinging every single member of the parent with the child, i thought there might be an easier way to assign the parents member all at once. Here is my thought.
class Human {
public $health = "200";
public function __construct( $health ) {
$this->health = $health;
}
}
class Monster extends Human {
public function __construct( \Human $human ) {
parent::$this = $human;
}
}
$unit = new \Monster( new \Human );
Is something similar or even is anything like this possible instead of this:
class Monster extends Human {
public function __construct( \Human $human ) {
$this->health = $human->health;
}
}
One way to accomplish this (doesn't use inheritance though) is to look at making a "humanize" function that adds the data/function(s) to your class as follows:
const humanize = (WrappedComponent, health) => {
let w = new WrappedComponent();
w.health = health;
w.getHealth = function() {
return this.health;
}
return w;
}
class Monster {
}
const monster = humanize(Monster, 200);
console.log(monster.getHealth());
What this does is allows you to "humanize" any class/object you like; when you do so, it adds health member and a getHealth function.