类中另一个对象的访问属性-PHP

时间:2020-06-11 14:06:19

标签: php

我一直在努力寻找解决方案,但我无法解决,因此我将在这里提出我的问题,希望它可以帮助其他人搜索相同的问题。

例如,我有一个基于“护甲”的物品类别。

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类,因为我将创建很多这样的新类,并且我希望所有Magic Armor上的相同属性都保留在一个地方-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
    }

那么我该如何做呢?原因是我将创建大量的这些,并且我希望所有这些对象都能从其他对象中寻找其基本属性。而且,如果我需要更改某个属性的值,则可以在以后减轻生活负担。

1 个答案:

答案 0 :(得分:1)

构造函数应将先前的盔甲作为参数,并可以引用其属性。

    public function __construct($armor) {
        $this->name = "Magic " . $armor->name;
        $this->defense = $armor->defense * 2;
        $this->durability = $armor->durability * 1.75;
    }

然后创建如下对象:

new MagicHeavyArmor($heavy_armor);
相关问题