首页 > 解决方案 > 将子类中的父变量分配为php中的传递实例

问题描述

我想将父类的一个实例传递给子类的构造函数,而不是将父类的每个成员都分配给子类,我认为可能有一种更简单的方法可以一次分配父类成员。这是我的想法。

class Human {
    public $health = "200";
    public function __construct( $health ) {
        $this->health = $health;
    }
}

class Monster extends Human {
    public function __construct( \Human $human ) {
        parent::$this = $human;
    }
}

$unit = new \Monster( new \Human );

是否有类似的东西,甚至是这样的东西,而不是这样:

class Monster extends Human {
    public function __construct( \Human $human ) {
        $this->health = $human->health;
    }
}

标签: phpoopinheritance

解决方案


实现这一点的一种方法(虽然不使用继承)是查看创建一个“人性化”函数,将数据/函数添加到您的类中,如下所示:

const humanize = (WrappedComponent, health) => {
  let w = new WrappedComponent();
  w.health = health;
  w.getHealth = function() {
    return this.health;
  }
  return w;
}

class Monster {
}

const monster = humanize(Monster, 200);
console.log(monster.getHealth());

它的作用是让你“人性化”任何你喜欢的类/对象;当您这样做时,它会添加健康成员和 getHealth 函数。


推荐阅读