Reputation: 325
I have been looking hard for a solution on this and i can't solve it so i will ask my question here and hopefully it will help others searching for the same question.
I have a Class for an items based on "Armor" for example.
class Armor {
public $name, $defense, $durability;
function __construct($name, $defense, $durability){
$this->name = $name;
$this->defense = $defense;
$this->durability = $durability;
}
}
Then i create a bunch of objects like this:
$heavy_armor = new Armor("Heavy Armor", 250, 50);
Then in a totally different file and use, I have another class for Magic Items which will create a brand new Magic Item but the base i want to use is the already existing heavy armor. However, there is a catch. I am already extending a different MagicArmors class because i will be creating a lot of these new classes and i want the common properties that will be the same across all Magic Armors to stay in one place - the MagicArmors class. Example:
class MagicHeavyArmor extends MagicArmors {
public function __construct() {
$this->name = "Magic Heavy Armor";
// so here i want to point to the Defense and Durability of the $heavy_armor object
$this->defense = 625; // Ideally i want $this->defense = $heavy_armor->defense * 2.5
$this->durability = 87.5; // Same here - I want $this->durability = $heavy_armor->durability * 1.75
}
So how do I make this work? The reason is that i will be creating a huge load of these and i want all of them to be able to looking for their base properties from other objects. And if i need to change a value of a property, to ease my life later.
Upvotes: 0
Views: 24
Reputation: 780798
The constructor should take the previous armor as a parameter, and can refer to its properties.
public function __construct($armor) {
$this->name = "Magic " . $armor->name;
$this->defense = $armor->defense * 2;
$this->durability = $armor->durability * 1.75;
}
Then you create the object like this:
new MagicHeavyArmor($heavy_armor);
Upvotes: 1