我一直在努力寻找解决方案,但我无法解决它,所以我将在这里提出我的问题,希望它能帮助其他正在寻找相同问题的人。
例如,我有一个基于“装甲”的物品的类。
class Armor {
public $name, $defense, $durability;
function __construct($name, $defense, $durability){
$this->name = $name;
$this->defense = $defense;
$this->durability = $durability;
}
}然后我创建了一堆对象,如下所示:
$heavy_armor = new Armor("Heavy Armor", 250, 50);然后在一个完全不同的文件和用途中,我有另一个魔法物品的类,它将创建一个全新的魔法物品,但我想使用的基础是已经存在的重型装甲。然而,这里有一个问题。我已经扩展了一个不同的MagicArmors类,因为我将创建许多这样的新类,并且我希望在所有魔法装甲中相同的公共属性留在一个地方- MagicArmors类。示例:
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
}那么我该怎么做呢?原因是我将创建大量的这些对象,并且我希望所有这些对象都能够从其他对象中查找它们的基本属性。如果我需要改变一个财产的价值,以方便以后的生活。
发布于 2020-06-11 22:18:04
构造函数应该将前一个装甲作为参数,并且可以引用它的属性。
public function __construct($armor) {
$this->name = "Magic " . $armor->name;
$this->defense = $armor->defense * 2;
$this->durability = $armor->durability * 1.75;
}然后创建对象,如下所示:
new MagicHeavyArmor($heavy_armor);https://stackoverflow.com/questions/62326288
复制相似问题