【发布时间】:2019-04-26 04:38:04
【问题描述】:
我正在尝试从一个基类实例化两个对象,并将一个参数从子类构造函数传递给父类构造函数。这似乎不起作用。就好像对象甚至不是父类的子对象一样。我不知道我做错了什么。
我已经尝试重新排列包含,不传递任何参数(这会导致错误,“需要一个参数”),以及其他修补都无济于事。
父类:
class SuperHero {
private $health;
private $name;
private $isDead;
public function __construct($name) {
$this->name;
$this->isDead = false;
}
// ...
public function attack($opponent) {
echo $this->name.' attacks '.$opponent->name.'!<br>';
$dmg = mt_rand(1, 10);
$opponentHealth = determineHealth($opponent, $dmg);
echo $opponent->name.' has '.$opponentHealth.' health left!<br>';
}
// ...
子类:
<?php
require_once('SuperHero.php');
class Batman extends SuperHero {
public function __construct() {
parent::__construct('Batman');
$this->health = mt_rand(1, 1000);
}
}
执行的脚本:
require_once('Batman.php');
require_once('Superman.php');
$h1 = new Batman;
$h2 = new Superman;
echo $h1->name.' is starting with '.$h1->health.' health!<br>';
echo $h2->name.' is starting with '.$h2->health.' health!<br>';
while($h1->getIsDead() == false && $h2->getIsDead() == false){
$h1->attack($h2);
$h2->attack($h1);
}
实际结果
is starting with 317 health!
Superman is starting with 300 health!
attacks !
预期结果
Batman is starting with 317 health!
Superman is starting with 300 health!
Batman attacks Superman!
【问题讨论】:
-
您实际上从未在任何时候设置
$this->name。 -
你在
Superhero构造函数中忘记了$this->name = $name;。 -
另外,您正在尝试访问
$opponent->name和$h1->health但name和health是私有的。您需要 getter 才能访问这些属性。 -
最后,你的整个设计都被窃听了。它使超人有可能击败蝙蝠侠;我们都知道这是不可能的。
标签: php oop inheritance