php - 将子类中的父变量分配为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;
}
}
解决方案
实现这一点的一种方法(虽然不使用继承)是查看创建一个“人性化”函数,将数据/函数添加到您的类中,如下所示:
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 函数。
推荐阅读
- r - 从数据表中删除具有特定字符串的行
- c# - visual studio winforms 无法使用移动图标移动
- python - 从两个列表中插入值 - ValueError:要解包的值太多(预期为 2)
- javascript - TypeError:无法从 Fetch 调用中读取未定义的嵌套 Json 的属性“fixtures”
- loops - Cplex:如何在 for 循环中从 dat.file 读取不同的数据输入
- java - Java SonarQube 错误“使公共静态字段最终化”
- c# - WPF:如何画一个圆?
- docker-compose - 看不到 Consul UI
- firebase - 我可以在 Firebase 身份验证中将身份验证提供商从谷歌帐户更改为匿名吗?
- ios - 空的手机号码在iOS中可以调用吗?