我对oop很陌生,我想弄清楚。我有以下哺乳动物类代码,我计划进一步发展。我有一个响应正确值的子类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();
我想得到的结果是:“灰熊有四个爪子。后代是活的,靠伐木业活动。他们吃三文鱼,咆哮着说:“我很感激你的帮助!
最佳答案
原因是bear类似乎不接受变量。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 - PHP子类不会覆盖新值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19329247/