我是 OOP 的新手,正在努力弄明白。我有以下哺乳动物类代码,我计划进一步开发。我有一个反射(reflect)正确值的子类 Bear,但我不能在子类 Grizzly 中重写 $name、$move、$ear 或 $sound 值。
abstract class Mammal
{
protected $name;
protected $limbs;
protected $offspring = 'live';
protected $move;
protected $eat;
protected $sound;
protected function __construct($name, $limbs, $offspring, $move, $eat, $sound) {
$this->name = $name;
$this->limbs = $limbs;
$this->offspring = $offspring;
$this->move = $move;
$this->eat = $eat;
$this->sound = $sound;
}
public function getOutput() {
echo "The {$this->name} has four {$this->limbs}. The offspring is birthed {$this->offspring} and move by {$this->move}. They eat {$this->eat} and talk by {$this->sound}.";
}
}
class Bear extends Mammal
{
public function __construct() {
Mammal::__construct('bear', 'claws', $this->offspring, '', '', '');
}
}
class Grizzly extends Bear
{
public function __construct() {
Bear::__construct('grizzly bear', 'claws', $this->offspring, 'lumbering', 'salmon', 'roaring');
}
}
$grizzly = new Grizzly;
$grizzly->getOutput();
我想要得到的输出是:“灰熊有四只爪子。后代是活生生的,靠笨拙移动。它们吃鲑鱼,靠吼叫说话。”感谢您的帮助!
最佳答案
原因是你的熊类似乎没有带变量。
class Bear extends Mammal
{
public function __construct() { //See, this constructor takes nothing
Mammal::__construct('bear', 'claws', $this->offspring, '', '', '');
}
}
下面是我做的事情
class Bear extends Mammal
{
public function __construct($bear = 'bear') {//right hear
Mammal::__construct($bear, 'claws', $this->offspring, '', '', '');
}
}
Your code in codepad.org with my little change
注意:我就是这样实现的
关于PHP 子类不会覆盖新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19329247/