簡體   English   中英

訪問class中另一個object的屬性 - PHP

[英]Access property of another object in a class - PHP

我一直在努力尋找解決方案,但我無法解決,所以我會在這里問我的問題,希望它能幫助其他人尋找同樣的問題。

例如,我有一個 Class 用於基於“Armor”的項目。

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);

然后在一個完全不同的文件和使用中,我有另一個 class 用於魔法物品,這將創建一個全新的魔法物品,但我想使用的基礎是已經存在的重型裝甲。 但是,有一個陷阱。 我已經擴展了一個不同的 MagicArmors class,因為我將創建很多這樣的新類,並且我希望所有 Magic Armors 都相同的公共屬性保留在一個地方 - MagicArmors class。示例:

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
    }

那么我該如何進行這項工作呢? 原因是我將創建大量的這些,我希望它們都能夠從其他對象中尋找它們的基本屬性。 如果我需要改變財產的價值,以減輕我以后的生活。

構造函數應該以之前的盔甲為參數,並且可以引用它的屬性。

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

然后像這樣創建 object:

new MagicHeavyArmor($heavy_armor);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM