简体   繁体   English

访问class中另一个object的属性 - PHP

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

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”的项目。

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.然后在一个完全不同的文件和使用中,我有另一个 class 用于魔法物品,这将创建一个全新的魔法物品,但我想使用的基础是已经存在的重型装甲。 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:我已经扩展了一个不同的 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
    }

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.如果我需要改变财产的价值,以减轻我以后的生活。

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:然后像这样创建 object:

new MagicHeavyArmor($heavy_armor);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM