gpt4 book ai didi

PHP 子类不会覆盖新值

转载 作者:搜寻专家 更新时间:2023-10-31 21:36:03 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com